【链表节点的定义】
typedef struct node
{
int data; //节点内容
node *next; //下一个节点
}node;
//创建单链表
node *create()
{
int i = 0; //链表中数据的个数
node *head, *p, *q;
int x = 0;
head = (node *)malloc(sizeof(node));
while(1)
{
cout<<"Please input the data:"<<endl;
cin >> x;
if(x == 0)
{
break;
}
p = (node*)malloc(sizeof(node));
p->data = x;
if(++i == 1) //链表只有一个元素
{
head->next = p; //连接到head的后面
}
else
{
p->next = p; //连接到链表尾端
}
q = p; //q指向末节点
}
q->next = NULL; //链表最后一个指针NULL
return head;
}
上面的代码中,使用while循环每次从终端读入一个整型数据,并调用malloc动态分配表节点内存存储这个整型数据,然后插入到单链表的末尾。最后,当数据为0时表示插入数据结束,此时把末尾节点的next指针置为NULL。
摘自《C和C++程序员面试秘笈》
本文介绍了一种使用C++实现单链表的方法,包括链表节点的定义及通过while循环从终端读取整数并将其插入到链表末尾的过程。最后,通过将末节点的next指针设为NULL来完成链表的创建。
444

被折叠的 条评论
为什么被折叠?



