linqy的个人博客分享 http://blog.sciencenet.cn/u/linqy

博文

简单链表的创建

已有 1568 次阅读 2017-6-26 19:49 |个人分类:C++|系统分类:科研笔记| 链表

#include <iostream>
using namespace std;
struct IntNode
{
    int data;
    IntNode* next;
};
void create( IntNode*& f,int n)
{
    if (n < 0)
    {
        cerr<<"n 值错误!"<<endl;
    }
    if (n == 0)
    {
        f == NULL;        
    }
    cout<<"输入"<<n<<"个数" <<endl;
    int x;
    IntNode* p = new IntNode;
    f = p;
    for (size_t i = 0;i < n; i++)
    {
        cin>>x;
        p->next = new IntNode;
        p = p->next;
        p->data = x;
    }
    p->next = NULL;
    f = f->next;
}
void create1( IntNode*& f,int n)
{
    if (n < 0)
    {
        cerr<<"n的值无效"<<endl;
    }
    if (n == 0)
    {
        f = NULL;
    }
    cout<<"从键盘上输入"<<n<<"个整数"<<endl;
    int x;
    f = NULL;
    while(n-- > 0)
    {
        IntNode* p = new IntNode;//由p指针指向一个新分配的节点
        cin>>p->data;
        p->next = f;
        f = p;//使f表头指针指向刚插入的拼接点
    }
}
void traverse(IntNode* f)
{
    while (f)
    {
        cout<<f->data<<"  "<<endl;//输出节点的值
        f = f->next;//得到下一个节点的指针
    }
    cout<<endl;
}
void main()
{
    IntNode *head1 = NULL, *head2 = 0;
    int n;
    cout<<"输入节点数:"<<endl;
    cin>>n;
    create(head1,n);
    traverse(head1);
    create1(head2,n);
    traverse(head2);
    system("pause");

}










https://blog.sciencenet.cn/blog-3134052-1063123.html

上一篇:c++在使用vector时,用完之后 需要释放吗?
下一篇:利用C++进行文件的创建与写入
收藏 IP: 124.207.244.*| 热度|

0

该博文允许注册用户评论 请点击登录 评论 (0 个评论)

数据加载中...
扫一扫,分享此博文

Archiver|手机版|科学网 ( 京ICP备07017567号-12 )

GMT+8, 2024-5-13 11:31

Powered by ScienceNet.cn

Copyright © 2007- 中国科学报社

返回顶部