c语言链表demo

发布时间 2023-08-02 20:09:51作者: steve.z

#include <stdio.h>
#include <stdlib.h>


// 定义节点结构体
struct node
{
    int data;
    struct node *next; /* 注意:这行使用了 node, node 必须在这行之前定义 */
};



int main(int argc, const char *argv[])
{
    // 1. 定义链表的头节点, 并初始化
    struct node *head = NULL;
    head = (struct node*)malloc(sizeof(struct node));
    if (head == NULL) {
        return 1;
    }
    head->data = 10;
    head->next = NULL;
    
    // 2. 向该链表中增加一个节点
    struct node* n = (struct node*)malloc(sizeof(struct node));
    if (n == NULL)
    {
        return 1;
    }
    n->data = 20;
    n->next =NULL;
    head->next = n;
    
    // 3. 遍历链表
    while (head != NULL) {
        printf("current node->data = %d\n", head->data);
        head = head->next;
    }
    
    // 4.
    
    
    return 0;
}