链表的定义:

typedef struct Node {
    int data;
    struct Node* next;
} Node;

头插法插入数据:

Node* headInsert(Node* head, int data) {
    Node* newNode = (Node*)malloc(sizeof(Node));
    newNode->data = data;
    newNode->next = head;
    head = newNode;
    return head;
}

尾插法插入数据:

Node* tailInsert(Node* head, int data) {
    Node* newNode = (Node*)malloc(sizeof(Node));
    newNode->data = data;
    newNode->next = NULL;
    if (head == NULL) {
        head = newNode;
    } else {
        Node* temp = head;
        while (temp->next != NULL) {
            temp = temp->next;
        }
        temp->next = newNode;
    }
    return head;
}

主函数调用:

int main() {
    Node* head = NULL; // 初始化链表头指针为空
    head = headInsert(head, 1); // 头插法插入1
    head = headInsert(head, 2); // 头插法插入2
    head = headInsert(head, 3); // 头插法插入3

    // 输出链表数据
    Node* temp = head;
    while (temp != NULL) {
        printf('%d ', temp->data);
        temp = temp->next;
    }
    printf('
');

    head = NULL; // 重置链表头指针为空
    head = tailInsert(head, 1); // 尾插法插入1
    head = tailInsert(head, 2); // 尾插法插入2
    head = tailInsert(head, 3); // 尾插法插入3

    // 输出链表数据
    temp = head;
    while (temp != NULL) {
        printf('%d ', temp->data);
        temp = temp->next;
    }
    printf('
');

    return 0;
}

输出结果:

3 2 1
1 2 3
C语言链表头插法和尾插法示例:插入数字1、2、3

原文地址: https://www.cveoy.top/t/topic/qhWe 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录