資料結構 鏈佇列

2021-10-04 18:15:10 字數 2786 閱讀 6343

鏈式佇列的實現思想同順序佇列類似,只需建立兩個指標(命名為 top 和 rear)分別指向鍊錶中佇列的隊頭元素和隊尾元素

圖 1 所示為鏈式佇列的初始狀態,此時佇列中沒有儲存任何資料元素,因此 top 和 rear 指標都同時指向頭節點。

在建立鏈式佇列時,強烈建議初學者建立乙個帶有頭節點的鍊錶,這樣實現鏈式佇列會更簡單。

由此,我們可以編寫出建立鏈式佇列的 c 語言實現**為:

//鍊錶中的節點結構

typedef

struct qnodeqnode;

//建立鏈式佇列的函式

qnode *

initqueue()

鏈式佇列資料入隊

鏈隊佇列中,當有新的資料元素入隊,只需進行以下 3 步操作:

將該資料元素用節點包裹,例如新節點名稱為 elem;

與 rear 指標指向的節點建立邏輯關係,即執行 rear->next=elem;

最後移動 rear 指標指向該新節點,即 rear=elem;

由此,新節點就入隊成功了。

例如,在圖 1 的基礎上,我們依次將 依次入隊,各個資料元素入隊的過程如圖 2 所示:

資料元素入鏈式佇列的 c 語言實現**為:

qnode*

enqueue

(qnode * rear,

int data)

鏈式佇列資料出隊 當鏈式佇列中,有資料元素需要出隊時,按照 「先進先出」

的原則,只需將儲存該資料的節點以及它之前入隊的元素節點按照原則依次出隊即可。這裡,我們先學習如何將隊頭元素出隊。

鏈式佇列中隊頭元素出隊,需要做以下 3 步操作:

通過 top 指標直接找到隊頭節點,建立乙個新指標 p 指向此即將出隊的節點; 將 p 節點(即要出隊的隊頭節點)從鍊錶中摘除; 釋放節點

p,**其所佔的記憶體空間; 我們將元素 1 和 2 出隊,

鏈式佇列中隊頭元素出隊的 c 語言實現**為:

void

dequeue

(qnode * top,qnode * rear)

// 1、

qnode * p=top->next;

printf

("%d"

,p->data)

; top->next=p->next;

if(rear==p)

free

(p);

}

c++實現鏈式鍊錶

#include

#include

typedef

struct qnodeqnode;

qnode *

initqueue()

qnode*

enqueue

(qnode * rear,

int data)

qnode*

dequeue

(qnode * top,qnode * rear)

qnode * p=top-

>next;

printf

("%d "

,p->data)

; top-

>next=p-

>next;

if(rear==p)

free

(p);

return rear;

}int

main()

執行結果為:

1 2 3 4

隊列為空

0

c++實現

#include

using

namespace std;

template

<

typename t>

// 結點

struct node

node

(const t& val, node

* thenext)

:value

(val)

,next

(thenext)};

template

<

typename t>

class

queue

// 向隊中加入元素

void

enqueue

(const t& e)

}// 刪除隊頭元素

bool

dequeue()

} t front()

bool

empty()

const

intsize()

const};

intmain()

cout <<

"出隊完成之後元素個數為: "

<< q.

size()

<< endl;

return0;

}

資料結構 鏈佇列

佇列沒完全看懂 include include define datatype int 定義節點結構 typedef struct nodequeuenode 定義頭節點 typedef structlinkqueue 初始化鏈佇列,頭節點置空 void initqueue linkqueue q ...

資料結構 鏈佇列

課程實驗,多有不足 include include include define true 1 define false 0 define ok 1 define error 0 typedef int queueelementtype typedef struct node linkqueueno...

資料結構鏈佇列實現

如題 這是一套完整的可執行的 需要讀者有一定的基礎去閱讀 語言是用c語言實現 在c 環境中編寫 在c 中可直接執行 在c語言中需要改部分標頭檔案和輸出語句 標頭檔案 這要是 的宣告部分 ifndef head define head include using namespace std typed...