C语言实现单链表对结点的删除以及插入,均在头和尾操作

    技术2024-07-02  102

    #include <stdio.h> #include <stdlib.h> struct Node { int data; struct Node *next; }; void printList(struct Node *pHead)//打印链表 { struct Node *p = pHead->next; while(p) { printf("%d\n",p->data); p = p->next; } } int isEmpty(struct Node *pHead)//判断是否空链表 { return pHead->next == NULL; } size_t length(struct Node *pHead)//统计有效结点 { struct Node *p = pHead->next; size_t counter = 0; while(p) { p = p->next; ++counter; } return counter; } void push_frnot(struct Node *pHead,int n)//头部插入法 { struct Node *pNew = malloc(sizeof(struct Node)); pNew->data = n; pNew->next = pHead->next; pHead->next = pNew; } void push_back(struct Node *pHead,int n)//尾部插入插法 { if(isEmpty(pHead)) { push_frnot(pHead,n); } else { struct Node *pNew = malloc(sizeof(struct Node)); pNew->data = n; struct Node *p = pHead->next; while(p->next) { p = p->next; } p->next = pNew; pNew->next = NULL; } } void pop_front(struct Node *pHead)//头部删除法 { if(!isEmpty(pHead)) { struct Node *p = pHead->next; pHead->next = p->next; free(p); } } void pop_back(struct Node *pHead)//尾部删除法 { if(length(pHead) >= 2) { struct Node *p = pHead->next; while(p->next->next) { p = p->next; } free(p->next); p->next = NULL; } else if(length(pHead) < 2) { pop_front(pHead); } } void destroyList(struct Node *pHead)//清除所有结点 { while(!isEmpty(pHead)) { pop_front(pHead); } } int main(void) { struct Node head; head.next = NULL; struct Node *pHead; pHead = &head;//定义一个空链表 //测试 push_frnot(pHead,1); push_frnot(pHead,2); push_frnot(pHead,3); push_back(pHead,5); pop_front(pHead); pop_back(pHead); printList(pHead); destroyList(pHead); printf("length = %u\n",length(pHead));//检查是否删除 return 0; }
    Processed: 0.008, SQL: 9