C语言链表——头插法和尾插法

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

typedef struct ListNode{
    int val;
    ListNode* next;
}Node_t, *pNode_t;

void print_list(ListNode *head) {
    ListNode *p = head;
    while (p != nullptr) {
        printf("%d ", p->val);
        p = p->next;
    }
}

void headInsert(pNode_t *p_p_head, pNode_t *p_p_tail, int val) {
    pNode_t pNew = (pNode_t)calloc(1,sizeof(Node_t));
    pNew->val = val;
    if (*p_p_head == NULL) {
        *p_p_head = pNew;
        *p_p_tail = pNew;
    }
    else {
        pNew->next = *p_p_head;
        *p_p_head = pNew;
    }
}

void tailInsert(pNode_t *p_p_head, pNode_t *p_p_tail, int val) {
    pNode_t pNew = (pNode_t)calloc(1, sizeof(Node_t));
    pNew->val = val;
    if (*p_p_head == NULL) {
        *p_p_head = pNew;
        *p_p_tail = pNew;
    }
    else {
        (*p_p_tail)->next = pNew;
        *p_p_tail = pNew;
    }
}

int main() {
    pNode_t head = nullptr;
    pNode_t tail = nullptr;
    int num = 0;
    while (scanf("%d", &num) != EOF) {
        tailInsert(&head, &tail, num);
    }
    print_list(head);
}

 

posted on 2021-02-02 20:59  平ping  阅读(447)  评论(0)    收藏  举报