怎么用C语言创建单链表

   2025-02-15 9690
核心提示:使用C语言创建单链表的基本步骤如下:定义一个结构体来表示链表的节点,该结构体包含两个成员:数据域和指针域。struct Node {in

使用C语言创建单链表的基本步骤如下:

定义一个结构体来表示链表的节点,该结构体包含两个成员:数据域和指针域。
struct Node {    int data;    struct Node* next;};
创建一个头节点,并将其指针域初始化为NULL。
struct Node* head = NULL;
定义一个函数来向链表中插入新节点。该函数接受一个整数作为参数,将其存储在新节点的数据域中,并将新节点插入到链表的末尾。
void insert(int data) {    struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));    newNode->data = data;    newNode->next = NULL;        if (head == NULL) {        head = newNode;    } else {        struct Node* current = head;        while (current->next != NULL) {            current = current->next;        }        current->next = newNode;    }}
定义一个函数来遍历并打印链表中的所有节点。
void printList() {    struct Node* current = head;    while (current != NULL) {        printf("%d ", current->data);        current = current->next;    }    printf("\n");}
编写主函数,调用上述函数来创建、插入和打印链表。
int main() {    insert(1);    insert(2);    insert(3);    printList();        return 0;}

以上代码将创建一个包含3个节点的单链表,并输出节点的值。输出结果为:1 2 3。你可以在此基础上进一步扩展链表的功能,比如插入、删除和查找节点等操作。

 
 
更多>同类维修知识
推荐图文
推荐维修知识
点击排行
网站首页  |  关于我们  |  联系方式  |  用户协议  |  隐私政策  |  网站留言