带头尾指针的单链表(带头指针和尾指针的单循环链表区别)

带头尾指针的单链表(带头指针和尾指针的单循环链表区别)可以使用如下代码实现单链表 不带头 节点 的建表 include lt stdio h gt include lt stdlib h gt typedef struct Node int data struct Node next Node Node createList Node head NULL

大家好,我是讯享网,很高兴认识大家。

可以使用如下代码实现单链表带头节点的建表:


讯享网

#include <stdio.h> #include <stdlib.h> typedef struct Node { int data; struct Node *next; } Node; Node *createList() { Node *head = NULL, *tail = NULL; int x; while (scanf("%d", &x) == 1) { Node *newNode = (Node *)malloc(sizeof(Node)); newNode->data = x; newNode->next = NULL; if (head == NULL) { head = tail = newNode; } else { tail->next = newNode; tail = newNode; } } return head; } void printList(Node *head) { Node *p = head; while (p != NULL) { printf("%d ", p->data); p = p->next; } printf(" "); } int main() { Node *head = createList(); printList(head); return 0; } 

讯享网

这段代码可以从标准输入中读入一些整数,然后创建一个单链表并返回头节点。在创建链表时,我们使用了一个尾指针 tail 来记录链表的尾部,这样可以避免每次插入都需要遍历整个链表。最后,我们可以使用 printList 函数来打印链表的所有元素。


小讯
上一篇 2025-05-28 11:22
下一篇 2025-06-09 23:38

相关推荐

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容,请联系我们,一经查实,本站将立刻删除。
如需转载请保留出处:https://51itzy.com/kjqy/151439.html