链表(建立)

xiaoxiao2021-02-28  123

【链表节点的定义】

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++程序员面试秘笈》

转载请注明原文地址: https://www.6miu.com/read-67105.html

最新回复(0)