單鏈表基本操作

2021-10-04 05:35:37 字數 3679 閱讀 1419

#include

using

namespace std;

#define maxsize 20

#define true 1

#define false 0

typedef

bool status;

/* status是函式的型別,其值是函f數結果狀態***/

typedef

char elemtype;

/* elemtype型別根據實際情況而定,這裡假設為int */

typedef

struct node linklist;

void

displaylist

(linklist* list)

cout << endl;

}void

initlist

(linklist*

& list)

void

createlistathead

(linklist*

& list, elemtype arr,

int len)

}void

createlistattail

(linklist*

& list, elemtype arr,

int len)

p->next =

null;}

status listinsert

(linklist*

& list,

int position, elemtype e)

if(count != position -1)

return false;

temp =

new node;

temp-

>data = e;

temp-

>next = p-

>next;

p->next = temp;

return true;

}status listdelete

(linklist*

& list,

int position, elemtype& e)

if(count != position -1)

return false;

temp = p-

>next;

e = temp-

>data;

p->next = p-

>next-

>next;

delete temp;

return true;

}void

clearlist

(linklist*

& list)

}status listempty

(linklist* list)

intlistlength

(linklist* list)

return count;

}status getelem

(linklist* list,

int position, elemtype& e)

e = p-

>data;

return true;

}int

locateelem

(linklist* list, elemtype e)

return0;

}void

destroylist

(linklist*

& list)

intmain()

;createlistattail

(l, c,5)

;// 3. 輸出鍊錶

cout <<

"3.輸出鍊錶"

<< endl;

displaylist

(l);

// 4. 輸出鍊錶的長度

cout <<

"4. 輸出鍊錶的長度"

<< endl;

cout <<

"鍊錶長度:"

<<

listlength

(l)<< endl;

// 5. 判斷鍊錶是否為空

cout <<

"5. 判斷鍊錶是否為空"

<< endl;if(

listempty

(l))

cout <<

"鍊錶為空"

<< endl;

else

cout <<

"鍊錶不為空"

<< endl;

// 6. 根據輸入位置,輸出列表的元素

cout <<

"6.輸入你要查詢的位置:"

; cin >> p;if(

getelem

(l, p, e)

) cout <<

"查詢成功\n"

<<

"在"<< p <<

"位置的值是:"

<< e << endl;

else

cout <<

"輸入範圍錯誤"

<< endl;

// 7. 輸出元素e的位置

cout <<

"7.輸入你要查詢的值:"

; cin >> e;if(

locateelem

(l, e)!=-

1)cout << e <<

"的第乙個位置是:"

<<

locateelem

(l, e)

<< endl;

else

cout <<

"順序表中沒有對應的值"

<< endl;

//8. 在第p個位置插入e元素

cout <<

"8.在第p個位置插入e元素"

<< endl;

cout <<

"輸入你要插入的值: "

; cin >> e;

cout <<

"輸入你要插入的位置: "

; cin >> p;if(

listinsert

(l, p, e)

) cout <<

"插入成功"

<< endl;

else

cout <<

"插入失敗"

<< endl;

// 9. 輸出鍊錶

cout <<

"9.輸出鍊錶"

<< endl;

displaylist

(l);

// 10. 刪除鍊錶的第p個元素

cout <<

"10. 刪除順序表的第p個元素"

<< endl;

cout <<

"輸入你要刪除的元素的位置:"

; cin >> p;if(

listdelete

(l, p, e)

)else

// 11. 輸出鍊錶

cout <<

"11.輸出鍊錶"

<< endl;

displaylist

(l);

// 12. 銷毀鍊錶

cout <<

"12.銷毀鍊錶"

<< endl;

destroylist

(l);

return0;

}

單鏈表基本操作

include include include include includeusing namespace std typedef struct node node,plinklist plinklist createfromhead node pstnode node malloc sizeof...

單鏈表基本操作

單鏈表的初始化,建立,插入,查詢,刪除。author wang yong date 2010.8.19 include include typedef int elemtype 定義結點型別 typedef struct node node,linkedlist 單鏈表的初始化 linkedlist...

單鏈表基本操作

include using namespace std define namelenth 20 define ok 0 define error 1 typedef struct flagnode node 生成結點 inline node newnode 銷毀化煉表 void destroylin...