24. 兩兩交換連結串列中的節點
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode() {} * ListNode(int val) { this.val = val; } * ListNode(int val, ListNode next) { this.val = val; this.next = next; } * } */ class Solution { public ListNode swapPairs(ListNode head) { ListNode dummy = new ListNode(0); dummy.next = head; ListNode curr = dummy; //add dummy node before head, and save the 0(crur.next) and 3(curr.next.next.next), and then connect // and then curr pointor move 2 postion. //頭節點前邊加dummy node,然後儲存頭節點(crur.next)跟index2(curr.next.next.next),交換後指標往後移動兩位 //一開始想複雜了,不需要兩個指標,也不需要用bealoon記錄是否移動過了。 while(curr.next != null && curr.next.next != null){ ListNode temp = curr.next; ListNode temp2 = curr.next.next.next; curr.next = curr.next.next; curr.next.next = temp; curr.next.next.next = temp2; curr = curr.next.next; } return dummy.next; } }
19.刪除連結串列的倒數第N個節點
class Solution { public ListNode removeNthFromEnd(ListNode head, int n) { ListNode dummy = new ListNode(0); dummy.next = head; ListNode fast = dummy; ListNode slow = dummy; //雙指標,一快一慢,快的多走n+1步,剛好走到null, 慢的走到要刪除的前一個。刪除。 //注意空指標異常 for(int i = 0; i <= n; i++){ fast = fast.next; } while(fast!=null){ fast = fast.next; slow = slow.next; } if(slow.next != null){ slow.next = slow.next.next; } return dummy.next; } }
面試題 02.07. 連結串列相交==160. Intersection of Two Linked Lists
public class Solution { public ListNode getIntersectionNode(ListNode headA, ListNode headB) { //到達統一長度後,一起往後走直到有相同的。如果沒有也是return null,都是A or b的其中一個。 //reference: https://www.youtube.com/watch?v=1bWqD_MwWuw if(headA == null || headB == null){ return null; } int lenA = len(headA); int lenB = len(headB); if(lenA > lenB){ while(lenA != lenB){ headA = headA.next; lenA--; } }else{ while(lenA != lenB){ headB = headB.next; lenB--; } } while(headA != headB){ headA = headA.next; headB = headB.next; } return headA; } public int len(ListNode list){ int len = 0; while(list != null){ list = list.next; len++; } return len; } }
142. Linked List Cycle II
public class Solution { public ListNode detectCycle(ListNode head) { //https://www.youtube.com/watch?v=ZJDClARjgDI //https://programmercarl.com/0142.%E7%8E%AF%E5%BD%A2%E9%93%BE%E8%A1%A8II.html#%E5%85%B6%E4%BB%96%E8%AF%AD%E8%A8%80%E7%89%88%E6%9C%AC ListNode fast = head; ListNode slow = head; while(fast.next != null && fast.next.next != null){ fast = fast.next.next; slow = slow.next; if(slow == fast){ ListNode index1 = head; ListNode index2 = fast; while(index1 != index2){ index1 = index1.next; index2 = index2.next; } return index1; } } return null; } }