帶頭節點的單迴圈鍊錶的插入 刪除 查詢等操作

2021-10-05 22:39:31 字數 3132 閱讀 5216

建立頭結點

#pragma once

typedef

struct cnode

cnode,

*clist;

//cnode*==clist

//初始化函式

void

initlist

(clist plist)

;//頭插

bool insert_head

(clist plist,

int val)

;//尾插

bool insert_tail

(clist plist,

int val)

;//在plist中查詢關鍵字key,找到返回結點,失敗返回null

cnode *

search

(clist plist,

int key)

;//判空

bool isempty

(clist plist)

;//刪除plist中的第乙個key

bool deleteval

(clist plist,

int key)

;//獲取資料長度

intgetlength

(clist plist)

;//輸出所有資料

void

show

(clist plist)

;//清空資料

void

clear

(clist plist)

;//銷毀動態記憶體

void

destroy

(clist plist)

;

建立list.cpp

#include

#include

#include

#include

"list.h"

//判空

static

void

deterpointnull

(clist plist)

}//初始化函式

void

initlist

(clist plist)

//頭插

bool insert_head

(clist plist,

int val)

//尾插

bool insert_tail

(clist plist,

int val)

//在plist中查詢關鍵字key,找到返回結點,失敗返回null

cnode *

search

(clist plist,

int key)

}return

null;}

//判空

bool isempty

(clist plist)

//刪除plist中的第乙個key

bool deleteval

(clist plist,

int key)

cnode *q;

for(q=plist->next;q!=

null

;q=q->next)

}return false;

}//獲取資料長度

intgetlength

(clist plist)

return count;

}//輸出所有資料

void

show

(clist plist)

printf

("\n");

}//清空資料

void

clear

(clist plist)

//銷毀動態記憶體

void

destroy

(clist plist)

}

補充功能模組:

1.已知遞增有序的單鏈表a,b,c分別儲存了乙個集合,設計演算法實現a:au(bnc),並使求解結構a仍保持遞增。

要求演算法的時間複雜度為o(|a|+|b|+|c|)。其中,|a|為集合a的元素個數

void

calculate

(plist plista,plist plistb,plist plistc)

p1=p1->next;

}else

if(p1->next->data==p2->data)

else

}else

if(p2->datadata)

else

if(p2->data>p3->data)}}

intmain()

2.試寫一演算法,對單鏈表實現就地逆置,時間複雜度為o(n)

//演算法1:利用棧實現(利用陣列模擬棧)//時間複雜度:o(n)  空間複雜度:o(n)

void

reverse1

(plist plist)

//金屬組中的資料從後往前,再賦值到鍊錶中

i=len-1;

//最後乙個元素的下標

for(node *p=plist->next;p!=

null

;p=p->next)

free

(arr);}

//演算法2:利用頭插和尾插相反的演算法 //o(n) o(1)

void

reverse

(plist plist)

}

小知識:

順序表和單鏈表效能對比:

1、插入:

順序表:頭插(o(n)需要將後面的資料後移),中間插入(o(n)需要將後面的資料後移),尾部插入(o(1))

鍊錶:頭插(o(1)不需要移動後面的資料),中間插入(o(1)不需要將後面的資料後移),尾部插入(o(1))

2、刪除

順序表:頭刪(o(n)需要將後面的資料後移),中間插入(o(n)需要將後面的資料前移),尾部插入(o(1))

鍊錶:頭插(o(1)不需要移動後面的資料),中間插入(o(1)不需要將後面的資料前移),尾部插入(o(1))

3、隨機訪問能力

順序表:o(1),通過下標直接訪問

鍊錶:o(n),必須從頭開始遍歷

不帶頭結點的單迴圈鍊錶

建立標頭檔案nlist.h pragma once 不帶頭節點的鍊錶,主要應用在迴圈鍊錶中,其缺點,操作複雜 會出現二級指標 優點 靈活 頭指標指向哪個節點哪個節點就是第乙個節點 不帶頭節點的單鏈迴圈鍊錶,尾節點的next指向第乙個節點 typedef struct nnode nnode,pnli...

帶頭節點的鍊錶

include include includetypedef int type typedef struct node node 建立乙個頭節點並將其指標返回 node node init 列印乙個鍊錶 void node display node head else printf n 找到第n個節...

迴圈鍊錶插入節點

由於迴圈鍊錶的迴圈特性,所以頭節點和尾節點可以被當成一般節點。所以,我們可以在寫迴圈鍊錶節點插入的函式中,可以呼叫自定義的函式 如下 void insert node list t insert node,list t prev node,list t next node 當我們寫插入函式的時候可以...