鏈表及其基本操作
文章目錄
- 鏈表及其基本操作
- 一、鏈表是什么?
- 二、鏈表是如何實作的
- 1.創建鏈表
- 2.輸出鏈表
- 三、基本操作(增刪改查插)
- 1.查找結點
- 2.洗掉結點
- 3.插入結點
- 4.清空結點
做為一名 新生蒟蒻來寫第一篇博客>
最近在發愁如何做出一個有意思的專案來挑戰自己,
但是因為能力有限被檔案和鏈表的基本操作搞暈了,
所以來學巨佬的博客來寫一寫最近所學的鏈表操作和我對鏈表的理解
歡迎指教
一、鏈表是什么?
鏈表在最開始學習的時候就聽說很難,但是去認真學習后卻發現鏈表非常的好玩 ,是對于結構體和指標的一種實際應用(個人理解),
那讓我們先來說說什么叫鏈表:
鏈表是一種常見的資料結構,它與常見的陣列是不同的,
使用陣列時先要指定陣列包含元素的個數,即為陣列的長度,
但是如果向這個陣列中加入的元素超過了陣列的大小時,便不能將內容全部保存,
鏈表這種存盤方式,其元素個數是不受限定的,當進行添加元素的時候存盤的個數就會隨之改變,
且對于元素的操作十分方便,
已經有大佬解釋的對于鏈表的好處解釋的十分清楚了,

二、鏈表是如何實作的
1.創建鏈表
最重要的是定義一個結構體,其中存放你要存盤的資料和你下個位置的地址,
struct nod
{
int date;
struct nod* next;
} ;
因為鏈表是分散的,在茫茫人海中要去找到它難如登天,所以要有“*next”指標來找到下一個nod的位置,
如圖

我們看到其中有有2個特殊的位置,首和尾(滑稽),這也是我們創捷鏈表和查找鏈表的重要位置,可以知道從何開始,到哪結束,(從哪來呀,到哪去),
struct nod* creat(int n)
{
struct nod * head = (struct nod *)malloc(sizeof(struct nod));
struct nod * end=head;
for(int i=0;i<n;++i)
{
struct nod * temp = (struct nod *)malloc(sizeof(struct nod));
scanf("%d",&temp->date);
end->next = temp;
end = temp;
}
end->next = NULL;
return head;
}
2.輸出鏈表
然后就是簡簡單單的輸出了:
void printlist(struct nod * head)
{
if(head == NULL)
return ;
struct nod * p = head;
while(p->next!=NULL)
{
p = p->next;//因為尾結點的next為空,為了可輸出其值,這樣巧妙使其可被輸出,
printf("%d",p->date);
}
return ;
}
三、基本操作(增刪改查插)
1.查找結點
回傳你需要查找的位置
struct nod * Findnod(struct nod * head,int a)
{
if(head == NULL)
return NULL;
struct nod * temp = head;
while(temp->next != NULL)
{
temp = temp->next;
if(temp->date == a)
return temp;
}
return NULL;//沒找到
}
2.洗掉結點
找到你要洗掉結點的前一個結點,然后是前結點的next等于該節點的next即可,
3.插入結點
與指定位置增加結點,并賦值,
void addnod(struct nod * head,int a)
{
if(head == NULL)
return ;
struct nod * temp = Findnod(head,a);
struct nod * newnod = (struct nod *)malloc(sizeof(struct nod ));
scanf("%d",&newnod->date);
newnod->next = temp->next;
temp->next = newnod;
return ;
}
4.清空結點
void FreeList()
{
//一個一個NULL
struct Node *temp =head; //定義一個臨時變數來指向頭
while (temp !=NULL)
{
// printf("%d\n",temp->a);
struct Node* pt =temp;
temp = temp->next; //temp指向下一個的地址 即實作++操作
free(pt); //釋放當前
}
//頭尾清空 不然下次的頭就接著0x10
head =NULL;
end =NULL;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/214247.html
標籤:其他
上一篇:小說瓦爾登湖單詞詞頻統計
