日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

快速入门无头双链表

發布時間:2025/3/20 编程问答 20 豆豆
生活随笔 收集整理的這篇文章主要介紹了 快速入门无头双链表 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

文章目錄

  • 無頭雙向單鏈表的基礎功能實現
    • 頭插法
    • 尾插法
    • 刪除第一次出現關鍵字為key的節點
    • 刪除所有的值為key的節點
    • 任意位置插入
    • 清空雙鏈表

無頭雙向單鏈表的基礎功能實現

在單鏈表的學習中,我們已經掌握了求單鏈表的長度,是否包含了某一個元素,以及打印單鏈表,無頭雙鏈表的求長度,判斷是否包含了某一個元素,打印雙鏈表,都是與單鏈表的寫法一樣的,所以這里就不在多做贅述。

頭插法

變化前

變化后

代碼實現:

//頭插法public void addFirst(int data){listnode add=new listnode(data);if (head==null){//還得考慮鏈表為空的情況head=add;last=add;return;}add.next=head;head.prve=add;head=add;}

尾插法

變化前

變化后

代碼實現:

//尾插法public void addLast(int data){listnode add=new listnode(data);if (head==null){//同樣需要考慮要是有空列表的情況head=add;last=add;return;}last.next=add;add.prve=last;last=add;}

刪除第一次出現關鍵字為key的節點

一般情況

出現在頭部情況(假設要刪除的第一次數據在頭部出現):

出現在尾部(假設要刪除的數據最后才第一次出現):

對以上情況進行分析之后,我們必須通過遍歷來解決,具體實現代碼如下:

//刪除第一次出現關鍵字為key的節點public void remove(int key){if (head==null)return;listnode cur=head;while (cur!=null){if (cur.val==key){if (cur==head){cur.next.prve=null;head=head.next;}else{cur.prve.next=cur.next;if (cur==last){last=cur.prve;}else{cur.next.prve=cur.prve;}}return;}else{cur=cur.next;}}}

但是在這里代碼是有缺陷的,因為如果就是一個節點的時候,那么此時代碼會報錯,我們就需要單獨討論一下,具體代碼實現如下:

public void remove(int key){if (head==null)return;listnode cur=head;while (cur!=null){if (cur.val==key){if (cur==head){head=head.next;if (head!=null){head.prve=null;}else{last=null;//尾節點要變成null,不然會被一直引用}}else{cur.prve.next=cur.next;if (cur==last){last=cur.prve;}else{cur.next.prve=cur.prve;}}}else{cur=cur.next;}}}

刪除所有的值為key的節點

這個就需要在刪第一次為key的基礎上,把return去掉,然后要讓cur一直往下走,具體實現代碼如下:

//刪除所有值為key的節點public void removeAllKey(int key){if (head==null)return;listnode cur=head;while (cur!=null){if (cur.val==key){if (cur==head){head=head.next;if (head!=null){head.prve=null;}else{last=null;}}else{cur.prve.next=cur.next;if (cur.next!=null){cur.next.prve=cur.prve;}else{last=last.prve;}}}cur=cur.next;}}

任意位置插入

插入前:

插入后

代碼實現如下:

//任意位置插入,第一個數據節點為0號下標public listnode search(int index){if (index<0||head==null)return null;listnode cur=head;while (index!=0){cur=cur.next;if (cur==null){//說明超出鏈表的長度return null;}index--;}return cur;}public void addIndex(int index,int data){listnode listnode=new listnode(data);if (index==0){//如果是第一個位置就是頭插法addFirst(data);return;}if (index==size()){//最后一個位置就是尾插法addLast(data);return;}listnode ret=search(index);if (ret==null)return;ret.prve.next=listnode;listnode.next=ret;listnode.prve=ret.prve;ret.prve=listnode;}

清空雙鏈表


代碼實現:

public void clear(){while(head!=null){listnode cur=head.next;head.prve=null;head.next=null;head=cur;}last=null;//要把尾節點手動置為null,不然還在被引用}

雙鏈表基本功能實現源碼
單鏈表的功能實現

總結

以上是生活随笔為你收集整理的快速入门无头双链表的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。