C語言 單鏈表的基本操作(增刪改查)

2022-06-21 10:00:16 字數 2241 閱讀 1464

這是尾插法單鏈表,單鏈表比較適合用來做佇列和棧,因為在鍊錶的頭和尾時的增刪改查的時間複雜度為o(1),而在鍊錶內部的增刪改查的平均時間複雜度為o(n)。

#include "

stdio.h

"#include

"stdlib.h"//

提供malloc()和free()

#include "

string.h

"#include

"time.h"//

提供strcpy(),time()等

//1.用結構體建立鍊錶節點

//乙個用來存放資料,另乙個存放指標

struct

node;//

2.全域性定義鍊錶頭尾指標,方便呼叫

struct node* head =null;

struct node* end =null;

//3.向鍊錶新增資料

void addlisttill(int

a )

else

end=temp; //

尾結點應該始終指向最後乙個}//

4.遍歷鍊錶並輸出

void

scanlist()}//

5.查詢指定的資料是否在鍊錶內

struct node* findnode(int

a ) temp = temp->next;

}//沒找到

return

null;

} //

6.刪除鍊錶

void

freelist()

//頭尾清空,不然下次的頭就接著0x10

head =null;

end =null;}//

7.在指定位置處插入資料

void addlistrand(int index,int

a)

struct node* pt =findnode(index);

if(null == pt) //

沒有此節點

//有此節點

//建立臨時節點,申請記憶體

struct node* temp =(struct node *)malloc(sizeof(struct

node));

//節點成員進行賦值

temp->data =a;

temp->next =null;

//連線到鍊錶上 1.找到的節點在尾部 2.找到的節點在中間

if (pt ==end)

else}//

8.刪除鍊錶末尾資料

void

deletelisttail()

//鍊錶不為空

//鍊錶有乙個節點

if (head ==end)

else

//找到了,刪尾巴

//釋放尾巴

free

(end);

//尾巴遷移

end=temp;

//尾巴指標為null

end->next =null;

}}//

9.刪除鍊錶的第乙個資料

void

deletelisthead()

head = head->next; //

頭的第二個節點變成新的頭

free

(temp);}//

10.刪除鍊錶指定的資料

void deletelistrand(int

a)

//鍊錶有東西,找這個節點

struct node* temp =findnode(a);

if(null ==temp)

//找到了,且只有乙個節點

if(head ==end)

else

if(head->next == end) //

有兩個節點

else

if(temp ==head)

}else

//多個節點

//找到了

//讓前乙個直接連線後乙個 跳過指定的即可

pt->next = temp->next;

free

(temp);

}}}//

主函式void

main()

else

}

以下是排序演算法的時間和空間複雜度表:

C語言單鏈表 增 刪 改 查

鍊錶是一種常見的基礎資料結構,結構體指標在這裡得到了充分的利用。鍊錶可以動態的進行儲存分配,也就是說,鍊錶是乙個功能極為強大的陣列,他可以在節點中定義多種資料型別,還可以根據需要隨意增添,刪除,插入節點。鍊錶都有乙個頭指標,一般以head來表示,存放的是乙個位址。鍊錶中的節點分為兩類,頭結點和一般節...

單鏈表的增刪改查操作

mark一下自己的學習過程,繼續堅持 linklist.cpp love created by wpln on 2018 11 8.include include include include using namespace std typedef struct studentstu,pstu d...

Java單鏈表增刪改查反轉基本操作

資料結構複習,是最好的說明。節點類 public class node public object getobject public void setobject object object public node getnext public void setnext node next 鍊錶類 ...