資料結構C語言實現----向連結串列中插入結點
阿新 • • 發佈:2020-07-13
1.明確在第幾個結點後插入
2.找到插入位置的前一個結點
3.交換指標:設插入位置的前一個結點為結點A , 插入的結點為結點B , 插入結點後面的一個節點為結點C
(1)結點B指向結點C
(2)結點A指向結點B
程式碼如下:
#include<stdio.h> #include<stdlib.h> typedef struct Node { char date; struct Node *next; }Node , *LinkList; //////////////////////////////// //建立一個連結串列 LinkList creatlinklist(int n) { LinkList New_node , Tail_node; LinkList Head_node=NULL; char c; for (size_t i = 0; i < n; i++) { printf("第%d個結點的資料為:",i+1); scanf("%c",&c); fflush(stdin); New_node = (LinkList)malloc(sizeof(Node)); New_node->date = c; New_node->next = NULL; if (Head_node ==NULL) { Head_node = New_node; }else { Tail_node->next = New_node; } Tail_node = New_node; } return Head_node; } ////////////////////////////// //向連結串列中插入結點 void insertlist(LinkList *List , int m , char insert_date) {//在連結串列List中,在第m個結點之後插入insert_date LinkList insert_node;//建立一個要插入的結點 insert_node = (LinkList)malloc( sizeof(Node) );//為這個節點申請空間 insert_node->date = insert_date;//把要插入的資料放入到這個結點中 if (*List == NULL) {//如果這個連結串列為空連結串列,則直接插入到第一個節點 *List = insert_node; insert_node->next = NULL; }else { LinkList befor_node = *List;//找到要插入位置的前一個結點 for (size_t i = 1; i < m; i++) { befor_node = befor_node->next; } insert_node->next = befor_node->next;//插入節點指向第三個結點(即前一個結點本來指向的結點) befor_node->next = insert_node;//前一個結點指向插入結點 } } int main() { int n; char c; LinkList List , List2; //List用於第一次列印單鏈表,List2用於第二次列印單鏈表 printf("請輸入結點個數:"); scanf("%d",&n); fflush(stdin); List = creatlinklist(n); List2 = List;//複製一遍連結串列,第一次列印連結串列後連結串列後頭指標會直接指向NULL,導致第二次列印失敗 printf("列印單鏈表:"); while ( List != NULL ) { printf("%c" , List->date); List = List->next; } putchar('\n'); /////////////////////////////// //插入結點 printf("在第幾個結點後面插入字元:"); scanf("%d",&n); fflush(stdin); printf("插入的字元為:"); scanf("%c",&c); fflush(stdin); insertlist(&List2 , n , c); printf("列印單鏈表:"); while ( List2 != NULL ) { printf("%c" , List2->date); List2 = List2->next; } return 0; }
執行結果: