在學習Linux之間我們先插入一下鏈表的知識
學習鏈表(一種數據結構思想)
鏈表和數組的區別和實現:
鏈表(鏈表是個好東西)
鏈表概念(什么是鏈表)?
鏈表就是數據結構->數據的存儲思想
鏈表的每一項都是一個結構體
????????說到數據存放,我們之前學過數組和結構體,而且數組一開始就把大小確認了比如int arr[10],還有地址也都是連續的,因此我們需要對數組或者結構體進行增刪改查的時候就會顯得很不靈活,因為內存消耗很大所以我們有了鏈表的概念
Tips回顧:
數組的特點:每個元素的地址是連續的
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? 鏈表的原理和解釋圖
鏈表的實現
t1是鏈表頭 ?有點像數組首地址通過p++得到后面的元素
鏈表的動態遍歷
添加上查找和計算鏈表元素個數的功能
這邊定義一個found是很巧妙的,count?不斷累加記錄節點數,found?記錄是否找到目標值。
????????使用?found?變量后,只需要在循環內部判斷是否找到目標值,若找到就將?found?置為?1?,循環結束后再根據?found?的值進行統一的輸出判斷,使代碼邏輯更加簡潔明了。
鏈表的從指定節點后方插入新節點
主要是insertBehindNum這段代碼
因為鏈表有增刪改查這些操作,所以這邊我直接把鏈表的增刪改查都寫出來
這個代碼里面包含了前插法(增),后插法(增),刪除指定元素,改元素,查元素其中前插法和后插法
代碼在這
#include <stdio.h>
struct Test
{
int data;
struct Test *next;
};
void printfInfo(struct Test *head)
{
struct Test *point;
point = head;
while(point !=NULL){
printf("%d ",point->data);
point =point->next;
}
putchar('\n');
}
int ?printfInfo1(struct Test *head,int data)
{
int count = 0;
int found = 0;
struct Test *point;
point = head;
while(point !=NULL){
count++;
if((point->data) == data){
found=1;
}
point = point->next;
}
if(found==1){
printf("have\n");
}else{
printf("no\n");
}
return count;
}
struct Test * gaiNum(struct Test *head,int data,int newdata)
{
struct Test *p;
p = head;
while(p !=NULL){
if(p->data == data){
p->data=newdata;
}
p = p->next;
}
return head;
}
struct Test *insertBehindNum(struct Test *head,int data,struct Test *new)
{
struct Test *p;
p=head;
while(p != NULL){
if(p->data == data){
new->next= p->next;
p->next ?= new;
return head;
}
????p = p->next;
}
return head;
}
struct Test *insertbeforeNum(struct Test *head,int data,struct Test *new)
{
struct Test *p;
p=head;
if(p->data == data){
new->next=p;
????printf("insert ok\n");
return new;
}
while(p->next != NULL){
if(p->next->data==data){
new->next = p->next;
??p->next = new;
??printf("insert ok\n");
??return head;
}
p = p->next;
}
return head;
}
struct Test *deleteNum(struct Test *head,int data)
{
struct Test *p;
p=head;
if(p->data == data){
p=p->next;
printf("delete ok\n");
return head;
}
while(p->next != NULL){
if(p->next->data == data){
p->next = p->next->next;
printf("delete ok~\n");
return head;
}
p = p->next;
}
return head;
}
int main()
{
?int count;
?struct Test *head = NULL;
?struct Test t1={1,NULL};
?struct Test t2={2,NULL};
?struct Test t3={3,NULL};
?struct Test t4={4,NULL};
?struct Test new={100,NULL};
?struct Test new2={999,NULL};
?struct Test new3={888,NULL};
?t1.next=&t2;
?t2.next=&t3;
?t3.next=&t4;
?printfInfo(&t1);
?count = printfInfo1(&t1,4);//查
?printf("鏈表元素個數為%d\n",count);
?head=insertBehindNum(&t1,3,&new);//在后方插入
?printfInfo(head);
?head = insertbeforeNum(&t1,3,&new2);//在前方插入
?printfInfo(head);
?head = insertbeforeNum(&t1,1,&new3);//在前方插入
?printfInfo(head);
?head = deleteNum(&t1,1);//刪除
?printfInfo(head);
?head = gaiNum(&t1,1,40);//改
?printfInfo(head);
?return 0;
}
????????看完之后是這樣的我們是初學者那么我們就不應該考慮鏈表的效率問題,我們要先理解鏈表的含義和和操作原理,那么我們之后有更好的基礎了之后,就可以去考慮鏈表的效率問題了。