Friday, February 23, 2018

174. Remove Nth Node From End of List

public class Solution {
    /*
     * @param head: The first node of linked list.
     * @param n: An integer
     * @return: The head of linked list.
     */
    public ListNode removeNthFromEnd(ListNode head, int n) {
        // write your code here
        // slow is point before target, fast gonna reach the end of list
        ListNode slow = head;
        ListNode fast = head;
       
        // There is n nodes between slow and fast
        for (int i = 0; i < n; i++) {
            fast = fast.next;
        }
       
        // Case: 1->null 1,  1->2->null 2
        if(fast == null) {
            head = head.next;
            return head;
        }
       
        while (fast.next != null) {
            fast = fast.next;
            slow = slow.next;
        }
       
        if (slow == head) {
            head = head.next;
        } else {
            slow.next = slow.next.next;
        }
       
        return head;
    }
}


public class Solution {
    /**
     * @param head: The first node of linked list.
     * @param n: An integer.
     * @return: The head of linked list.
     */
    ListNode removeNthFromEnd(ListNode head, int n) {
        // write your code here
        if (head == null) {
            return head;
        }
        
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        head = dummy.next;
        
        ListNode p1 = dummy;
        ListNode p2 = dummy;
        
        for (int i = 0; i < n; i++) {
            p1 = p1.next;
        }
        while (p1.next != null) {
            p1 = p1.next;
            p2 = p2.next;
        }
        p2.next = p2.next.next;
        
        return dummy.next;
    }
}

No comments:

Post a Comment

4. Ugly Number

1*2(t2) 2*2 3*2 (t3)1*3 2*3 3*3 (t5)1*5 2*5 3*5 1*2 2*2(t2) 3*2 1*3(t3) 2*3 3*3 (t5)1*5 2*5 3*5 Solution: public int nthUglyNumbe...