鏈表的基本操作(創建鏈表,查詢元素,刪除元素,插入元素等)


復習一下鏈表,參考書目為:算法筆記

 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 struct node 
 4 {
 5     int data;
 6     node* next;
 7 };
 8 //創建鏈表 
 9 node* create(int Array[])
10 {
11     node *p,*pre,*head;//pre保存當前結點的前驅結點,head為頭結點 
12     head = new node;//頭結點的創建 
13     head->next=NULL;//頭結點不需要數據域,指針域初始為NULL 
14     pre=head;//記錄pre為head 
15     for(int i=0;i<10;i++){
16         p=new node;//新建結點 
17         p->data=Array[i];//賦值 
18         p->next=NULL;//新結點指針域設置為NULL 
19         pre->next=p;//前驅結點的指針域指向新結點 
20         pre=p;//把pre設為p,作為下個結點的前驅結點 
21     }
22     return head;//返回頭結點指針 
23 }
24 //查找元素 
25 //帶有head頭結點的鏈表統計數據域為x的結點個數 
26 int search(node* head,int x)
27 {
28     int count=0;//計數器 
29     node* p=head->next;//從第一個結點開始 
30     while(p!=NULL){//循環遍歷鏈表 
31         if(p->data==x) count++;//值相等count加一 
32         p=p->next;
33     }
34     return count;
35 }
36 //插入元素
37 //將x插入以head為頭結點的鏈表的第pos和位置上 
38 void insert(node* head,int pos,int x)
39 {
40     node* p=head;
41     for(int i=0;i<pos-1;i++){
42         p=p->next;
43     }
44     node* q=new node;//創建新結點 
45     q->data=x;
46     q->next=p->next;
47     p->next=q;
48 } 
49 //刪除元素
50 //刪除以head為頭結點的鏈表中所有數據域為x的結點
51 void del(node* head,int x)
52 {
53     node* p=head;//頭結點 
54     p=p->next;//頭結點后的第一個結點
55     node* pre =head;
56     while(p!=NULL){
57         if(p->data==x){
58             pre->next=p->next;
59             delete(p);
60             p=pre->next;
61         }else{//數據域不是x,把pre和p都后移一位 
62             pre=p;
63             p=p->next;
64         }
65     } 
66 } 
67 int main()
68 {
69     int Array[10]={5,3,6,1,2,3,3,6,3,8};
70     node* L=create(Array);//新建鏈表,返回頭指針head賦值給L 
71     node* q=L;//頭結點; 
72     L=L->next;//頭結點后面接的第一個帶有數據域的結點 
73     printf("輸出所建鏈表的元素:");
74     while(L!=NULL){
75         printf("%d ",L->data);//輸出每個結點的數據域 
76         L=L->next;
77     }
78     //統計元素3的個數
79     printf("\n查找元素為3的個數為:%d\n",search(q,3)); 
80     //刪除元素為6的結點
81     del(q,6); 
82     printf("刪除素為6的結點之后的鏈表;"); 
83     L=q->next;//頭結點后面接的第一個帶有數據域的結點 
84     while(L!=NULL){
85         printf("%d ",L->data);//輸出每個結點的數據域 
86         L=L->next;
87     }
88     //在第5個位置插入元素1000
89     insert(q,5,1000);
90     printf("\n在第5個位置插入元素為100的結點之后的鏈表;");
91     L=q->next;//頭結點后面接的第一個帶有數據域的結點 
92     while(L!=NULL){
93         printf("%d ",L->data);//輸出每個結點的數據域 
94         L=L->next;
95     }
96     return 0;
97 }

運行結果如下圖:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM