生活随笔
收集整理的這篇文章主要介紹了
五个常见链表操作
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
- 單鏈表反轉
- 鏈表中環的檢測
- 兩個有序鏈表合并
- 刪除鏈表中倒數第n個結點
- 求鏈表的中間結點
封裝的Node信息如下:后面代碼不再給出
package cn.wangbo.list;
/*
* 這是鏈表類,
* 封裝了鏈表節點信息
* */
public class Node<T> {T val; //值Node next; //next指針public Node() {}public Node(T val, Node next) {this.val = val;this.next = next;}
}
單鏈表反轉
單鏈表反轉,只需要將每個結點的next指針指向其前驅結點。這個過程中,為了避免斷鏈,我們需要新建三個結點記錄當前結點、當前結點的前驅結點、當前結點的下一結點
Node<String> preNode = new Node<String>();Node<String> curNode = list;//list是鏈表頭指針Node<String> nextNode = new Node<String>();//反轉指針while (curNode.next != null){nextNode = curNode.next;curNode.next = preNode;preNode = curNode;curNode = nextNode;}curNode.next = preNode;
鏈表中環的檢測
這里可以采用快慢指針法。快指針每次走兩步、慢指針每次走一步。如果快慢指針相遇,則說明有環,否則如果快指針走到終點(null)則說明無環。
public static boolean ringTest(Node node){if (node == null){return false;}Node slowNode = node;Node fastNode = node.next;while (fastNode.next != null && fastNode != null){slowNode = slowNode.next;fastNode = fastNode.next.next;if (fastNode == null){return false;}else if (fastNode == slowNode){return true;}}return false;}
兩個有序鏈表合并
兩個有序鏈表合并思路并不復雜,但是千萬要注意最后不要忘記指向剩下沒有指向過的結點。
static Node Merge(Node<Integer> node1,Node<Integer> node2){Node pNode = new Node();Node<Integer> node = pNode;if (node1 == null) return node2;else if (node2 == null) return node1;while (node1 != null && node2 != null){if (node1.val <= node2.val){node.next = node1;node1 = node1.next;}else{node.next = node2;node2 = node2.next;}node = node.next;}if (node1 == null){node.next = node2;}else if (node2 == null){node.next = node1;}return pNode.next;}
刪除鏈表中倒數第n個結點
如果采用兩次遍歷的話自然非常簡單,但是如果要求只遍歷一次怎么做呢?首先用兩個指針指向head結點,把第一個指針指向第n個結點,然后同時將兩個指針往后一步步移動,當第一個指針的next指向null的時候,第二個指針指向第倒數n-1個結點,sNode.next = sNode.next.next即完成刪除
public static Node<Integer> delete(Node<Integer> head,int n){Node<Integer> fNode = head;Node<Integer> sNode = head;for (int i = 0;i < n;i++){fNode = fNode.next;}//如果鏈表長度為nif (fNode == null){head = head.next;return head;}while (fNode.next != null){sNode = sNode.next;fNode = fNode.next;}sNode.next = sNode.next.next;return head;}
求鏈表的中間結點
這里同樣是采用快慢指針法。快指針每次走兩步,慢指針每次走一步,當快指針走完整個鏈表的時候,慢指針剛好走到鏈表的中間節點
public static Node<Integer> getMid(Node<Integer> node){Node<Integer> fastNode = node;Node<Integer> slowNode = node;while (fastNode != null && fastNode.next != null){fastNode = fastNode.next.next;slowNode = slowNode.next;}return slowNode;}
轉載于:https://www.cnblogs.com/wangbobobobo/p/10539428.html
總結
以上是生活随笔為你收集整理的五个常见链表操作的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。