線性表 鍊錶

2021-10-19 08:54:25 字數 3526 閱讀 5255

帶頭結點

initlist(linklist& l) 初始化,時間複雜度o(1)

listinsert(linklist& l, int i, elemtype e) 指定位序後插,時間複雜度o(n)

listdelete(linklist& l, int i, elemtype& e) 位序刪除元素,傳回結點元素,時間複雜度o(n)

getelem(linklist l, int i) 按位查詢,傳回第乙個結點元素等e的結點,時間複雜度o(n)

#include

using

namespace std;

#define elemtype int

#define maxsize 2

typedef

struct lnode lnode,

* linklist;

//初始化,時間複雜度o(1)

bool

initlist

(linklist& l)

l->next =

null

;return

true;}

//指定位序後插,時間複雜度o(n)

bool

listinsert

(linklist& l,

int i, elemtype e)

lnode* p = l;

//定義當前指標指向頭結點

int j =0;

//當前指標位於第幾位結點

while

(p !=

null

&& j < i -1)

/*****************/

if(p ==

null

)//先令插入的結點next指向下乙個結點

//再讓上乙個結點(p)指向插入的結點

lnode* s =

new lnode;

s->data = e;

s->next = p-

>next;

p->next = s;

/*****************/

//可以直接用後面「insertnextnode」函式簡化

return

true;}

//位序刪除元素,傳回結點元素,時間複雜度o(n)

bool

listdelete

(linklist& l,

int i, elemtype& e)

lnode* p = l;

int j =0;

while

(p !=

null

&& j < i -1)

//判斷第i-1個結點是否存在

//判斷是否結尾(if i = 4,長度為3,i-1個結點為結尾,i超出範圍)

if(p ==

null

|| p-

>next ==

null

) lnode* d = p-

>next;

e = d-

>data;

p->next = d-

>next;

delete d;

//釋放結點空間

return

true;}

//按位查詢,傳回第乙個結點元素等e的結點,時間複雜度o(n)

其他操作

//指定結點前插,時間複雜度o(1)

/*因為指定結點的前乙個結點是未知的

所以無法實現前驅結點指標->next = s

但可以指定結點稱為前驅結點,交換資料

*/bool

insertpriornode

(lnode* p, elemtype e)

lnode* s =

new lnode;

s->data = p-

>data;

//交換資料

p->data = e;

s->next = p-

>next;

p->next = s;

return

true;}

//按值查詢,傳回第乙個結點元素等e的結點,時間複雜度o(n)

lnode*

locateelem

(linklist l, elemtype e)

return p;

}//獲取鍊錶長度,時間複雜度o(n)

intlistlength

(linklist l)

/*或者

for (lnode* p = l; p->next != null; p = p->next)

*/return len;

}

不帶頭結點
bool

initlist

(linklist& l)

//指定位序插入,時間複雜度o(n)

bool

listinsert

(linklist& l,

int i, elemtype e)

else

if(i ==1)

lnode* p = l;

//定義當前指標指向第1個結點

int j =1;

//當前指標指向第1位結點

while

(p !=

null

&& j < i -1)

if(p ==

null

)//先令插入的結點next指向下乙個結點

//再讓上乙個結點(p)指向插入的結點

lnode* s =

new lnode;

s->data = e;

s->next = p-

>next;

p->next = s;

return

true

;}

線性表 鍊錶

線性表的adt list.h 線性表的c 抽象類宣告 templateclass list 單鏈表節點的定義 link.h 單鏈表節點類的定義 template class link link link nextval null 鍊錶的實現宣告 成員函式的是實現 鍊錶的實現宣告 include st...

線性表 鍊錶

include include typedef int elemtype typedef struct node lnode,linklist linklist createlinklist1 頭插法 linklist createlinklist2 尾插法 void lengthlinklist ...

線性表,鍊錶

資料的儲存結構分為鏈式儲存結構,線性儲存結構。不管什麼型別的資料結構,都會以這兩種儲存方式在計算機中儲存。線性儲存結構就是開闢一段連續的記憶體 記憶體大小已經確定 將資料儲存在這段連續記憶體中,這種儲存結構的優點是可以快速地取出元素,時間複雜度為o 1 缺點是插入和刪除需要移動大量的元素,時間複雜度...