1. 程式人生 > >C語言鏈表的增刪查改

C語言鏈表的增刪查改

頭插法 delete 空間 spa empty 初始 free clu eof

小經驗:在VS2017中,使用while(scanf(“%d”,&i)!= NULL){......}時,結束輸入需要輸入三次ctrl+z+空格

func.h

#include <stdlib.h>
#include <string.h>

typedef struct student {
    int number;
    struct student* pnext;
}stu, *pstu; 

void list_print(pstu);//打印
void list_head_insert(pstu*,pstu*,int
);//頭插法 void list_tail_insert(pstu*, pstu*, int);//尾插法 void list_sort_insert(pstu*, pstu*, int);//有序插入 void list_delete(pstu*, pstu*, int);//節點刪除

func.c

#include "func.h"

void list_head_insert(pstu* pphead, pstu* pptail, int i) 
{//頭插法
    pstu pnew;
    pnew = (pstu)malloc(sizeof(stu));//申請空間
    memset(pnew,0
,sizeof(stu));//初始化 pnew->number = i; if (*pphead == NULL) {//鏈表為空,新節點既是頭指針,又是尾指針 *pphead = pnew; *pptail = pnew; } else { pnew->pnext = *pphead;//原有的鏈表頭作為新節點的pnext *pphead = pnew;//新節點作為節點頭 } } void list_tail_insert(pstu* pphead, pstu* pptail, int
i) {//尾插法實現 pstu pnew; pnew = (pstu)calloc(1, sizeof(stu));//calloc會進行空間初始化 pnew->number = i; if (*pptail == NULL) { *pphead = pnew; *pptail = pnew; } else { (*pptail)->pnext = pnew;//新節點變成原有尾節點的pnext *pptail = pnew;//新節點變成尾節點 } } void list_sort_insert(pstu* pphead, pstu* pptail, int i) {//有序插入實現 pstu pcur,ppre;//遊標 pcur = *pphead; ppre = *pphead; pstu pnew; pnew = (pstu)calloc(1, sizeof(stu));//calloc會進行空間初始化 pnew->number = i; if (*pptail == NULL) {//鏈表為空 *pphead = pnew; *pptail = pnew; } else if (i<(*pphead)->number)//小於頭結點,類似頭插法 { pnew->pnext = *pphead;//原有的鏈表頭作為新節點的pnext *pphead = pnew;//新節點作為節點頭 }else { while (pcur!=NULL) {//插入中間 if (i<pcur->number) { ppre->pnext = pnew; pnew->pnext = pcur; break; } ppre = pcur; pcur = pcur->pnext; } if (pcur == NULL) {//pcur為null,說明插入尾節點 (*pptail)->pnext = pnew; *pptail = pnew; } } } void list_delete(pstu* pphead, pstu* pptail, int d) {//刪除實現 pstu ppre = *pphead, pcur = *pphead; if (*pphead == NULL) //鏈表為空 { printf("List is empty\n"); return; }else if(pcur->number==d)//頭結點刪除 { *pphead = pcur->pnext; if (*pphead == NULL) {//刪除節點後,鏈表為空 *pptail = NULL; } free(pcur); }else//刪除中間和尾部 { while (pcur != NULL) { if (pcur->number == d) { ppre->pnext = pcur->pnext; break; } ppre = pcur; pcur = pcur->pnext; } if (pcur==*pptail) //刪除的是尾節點 { *pptail = ppre; } if (pcur == NULL) //未找到節點 { printf("This node is not in list\n"); } else { free(pcur); } } } void list_print(pstu phead) { while (phead != NULL) { printf("%3d", phead->number); phead = phead->pnext; } printf("\n"); }

main.c

#include "func.h"

int main() {
    pstu phead = NULL;
    pstu ptail = NULL;
    int i;
     while(scanf("%d",&i)!=EOF)
    {
        //list_head_insert(&phead, &ptail,i);//頭插法
        //list_tail_insert(&phead, &ptail, i);//尾插法
        list_sort_insert(&phead, &ptail, i);//有序插入
    }
    list_print(phead);
    while (scanf("%d", &i) != EOF) {
        list_delete(&phead, &ptail, i);
        list_print(phead);
    }
    system("pause");    
}

C語言鏈表的增刪查改