雙鏈表的沒一個元素都是對象,每個對象包含一個關鍵字域和兩個指針域(next,prev)。當然,每個對象還可能包含一些其他的衛星數據。next指向後繼節點,prev指向前驅節點。如果prev[x] == null,則無前驅節點,是head頭節點。如果next[x] == null則無後繼節點,是最後一個節點,即尾節點tail。
雙鏈表的具體操作如下:
雙向鏈表的插入:insert(L, x)
next[x]=head[L] //頭插法,當前節點x的下一個節點指向頭節點
if head[L] != null // 頭節點不爲空
then prev[head[L]] = x //頭節點的上一個節點指向x
head[L] = x //重置頭節點
prev[x] = null //頭節點的上一個節點置爲空
搜索:
search(L, k)
x = head[L]
while x != null and key[x] != k
do x = next[x]
return x;
刪除:
delete(L, x)
if(prev[x] != null) //如果當前節點不是頭節點
then next[prev[x]] = next[x] //當前節點x的上個節點的下一個節點置爲當前節點x的下一個節點
else head[L] = next[x] //否則頭節點置爲當前節點x的下一個節點
if next[x] != null
then prev[next[x]] = prev[x] // 當前節點x的下個節點的上一個節點置爲當前節點x的上一個節點
哨兵nil[L],有其他元素一樣的各個域
可以簡化邊界條件,將雙向鏈表變成帶哨兵的環形雙向鏈表,哨兵元素介於頭和尾之間,next[nil[L]]指向頭節點,prev[nil[L]]指向尾節點,同樣表頭的prev域和表尾的next域都指向nil[L],這樣可以吧head[L]換成next[nil[L]]。
插入:
next[x] = next[nil[L]]
prev[next[nil[L]] = x
next[nil[L]] = x
prev[x] = null
刪除:
next[prev[x]] = next[x]
prev[next[x]] = prev[x]