My LeetCode Diary - Day4 LinkedList

24. Swap Nodes in Pairs

Link

images

/**
 * 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(-1);
       dummy.next = head;
       ListNode cur = dummy;
       ListNode temp; //node3
       ListNode first; //node1
       ListNode second; //node2
       while (cur.next != null && cur.next.next != null) {
           first = cur.next;
           second = cur.next.next;
           temp = cur.next.next.next;
           cur.next = second;
           cur.next.next = first;
           cur.next.next.next = temp;
           cur = cur.next.next;
       }
       return dummy.next;
    }
}

19. Remove Nth Node From End of List

Link

images

/**
 * 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 removeNthFromEnd(ListNode head, int n) {
        ListNode dummy = new ListNode(-1);
        dummy.next = head;
        ListNode fastPointer = dummy;
        ListNode slowPointer = dummy;

        for(int i = 0; i < n; i++){
            fastPointer = fastPointer.next;
        }

        fastPointer = fastPointer.next;

        while (fastPointer != null) {
            fastPointer = fastPointer.next;
            slowPointer = slowPointer.next;
        }
        slowPointer.next = slowPointer.next.next;
        return dummy.next;
    }
}

142. Linked List Cycle II

Link

images

/**
 * Definition for singly-linked list.
 * class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public ListNode intersection(ListNode head) {
        ListNode slow = head;
        ListNode fast = head;
        while (fast != null && fast.next != null) {
            slow = slow.next;
            fast = fast.next.next;
            if (slow == fast) {
                return slow;
            }
        }
        return null;
    }

    public ListNode detectCycle(ListNode head) {
        if (head == null || head.next == null) {
            return null;
        }
        ListNode intersect = intersection(head);
        if (intersect == null) {
            return null;
        }

        ListNode start = head;
        while (intersect != start) {
            start = start.next;
            intersect = intersect.next;
        }
        return start;
    }
}