C语言程序设计 细节总结(链表)
12 鏈表
12.1 鏈表概述
1.采用動態存儲分配的一種重要數據結構,一個鏈表中存儲的是一批同類型的相關聯數據
2.動態分配時,每個結點之間可以不連續,結點之間的聯系可以用指針實現,每個結點分兩個域:數據域和指針域
12.2 處理動態鏈表所需函數(需要包含頭文件stdlib.h)
1.分配內存空間函數malloc()
(1)函數調用形式:(類型說明符*)malloc(size)
(2)malloc函數要求系統在內存分配一塊長度為size字節的連續區域,函數返回值為區域首地址
(3)函數返回的指針是無類型的,(類型說明符*)表示把返回值強制轉換為該類型指針
(4)例如,p=(char*)malloc(100); //表示分配100個字節的內存空間,強制轉換為字符數組類型,函數返回值為指向該字符數組的指針,把該指針賦給指針變量p
2.分配內存空間函數calloc()
(1)函數調用形式:(類型說明符*)calloc(n,size)
(2)calloc函數要求系統在內存動態存儲區分配n塊長度為size字節的連續區域
(3)例如,ps=(struct stu *)calloc(2,sizeof(struct stu));
3.釋放內存空間函數free()
(1)函數調用形式:free§
(2)釋放指針變量p所指向的一塊內存區域
12.3 單鏈表基本操作
1.建立鏈表
(1)調用malloc()函數向系統申請一個結點的存儲空間
(2)輸入該結點的值,并把該節點的指針成員設置為0
(3)把該結點加入鏈表中,如果鏈表為空,則該結點為鏈表頭結點,否則該結點加入表尾
2.鏈表查找
3.插入結點
(1)調用malloc()函數分配一個結點空間,并輸入新節點的值
(2)查找合適的插入位置
(3)修改相關節點的指針域
4.刪除結點
(1)從表頭結點開始,確定要刪除結點的地址q,以及q的前一個結點p的地址
(2)如果q為頭結點,刪除后應修改表頭指針head,否則修改結點p的指針域
(3)回收結點q的空間
代碼:
#include<stdio.h>
#include<stdlib.h>
struct node //定義結點結構
{int num;int score;struct node *next;
};
//1.創建鏈表
struct node *creat(struct node *head,int n)
{struct node *p,*q;for(int i=1; i<=n; i++){q=(struct node *)malloc(sizeof(struct node)); //申請結點空間scanf("%d%d",&q->num,&q->score); //輸入結點值q->next=NULL; //指針成員設為NULLif(head==NULL) //如果鏈表為空,該結點為鏈表頭結點{head=q;}else //否則加入表尾{p->next=q;}p=q; //q賦給p,為下一次q開辟空間保留上一次結點地址}return head;
};
//2.輸出鏈表
void print(struct node *head)
{struct node *p;p=head;while(p!=NULL){printf("%d %d\n",p->num,p->score);p=p->next;}
}
//3.鏈表查找
void find(struct node *head)
{int x;printf("請輸入要查找的序號:\n");scanf("%d",&x);struct node *p;p=head;while(p!=NULL&&p->num!=x){p=p->next;}if(p){printf("num=%d\tscore=%d\n",p->num,p->score);}else{printf("%d not be found!\n",x);}
}
//4.插入結點
struct node *insert(struct node *head)
{struct node *p,*q,*p1;q=(struct node*)malloc(sizeof(struct node)); //為新結點申請空間printf("請輸入要插入的結點(序號、分數):\n");scanf("%d%d",&q->num,&q->score);//在空表中插入if(head==NULL){q->next=NULL;head=q;return head;}//新結點插入表頭之前if(head->num > q->num){q->next=head;head=q;return head;}//在鏈表中查找插入位置p=head;p1=head->next;while(p1!=NULL&&p1->num < q->num){p=p1; //循環結束后p是上一結點p1=p1->next; //循環結束后p1是插入位置下一結點}q->next=p1;p->next=q;return head;
};
//5.刪除結點
struct node *dele(struct node *head)
{int i,x;printf("請輸入要刪除的序號:\n");scanf("%d",&x);struct node *p,*q;q=head;while(q!=NULL&&q->num!=x){p=q; //保留上一結點地址q=q->next;}if(q==NULL){printf("not found!");}else{if(q==head){head=q->next;}else{p->next=q->next;}free(q);}return head;
};
int main()
{struct node *head=NULL; //定義表頭指針head=creat(head,5);print(head);find(head);head=insert(head);print(head);head=dele(head);print(head);return 0;
}
總結
以上是生活随笔為你收集整理的C语言程序设计 细节总结(链表)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 亏吗 希望详细点 我会给分
- 下一篇: 弹弹堂现在还有领养中心吗