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; }
運行結果: