Friday, November 6, 2015

[leetcode] Remove Nth Node From End of List

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
public class Solution {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode fast = head;
        for (int i = 0; i < n; i++){
            fast = fast.next;
        }
        ListNode previous = dummy;
        ListNode current = head;
        ListNode dummy = new ListNode(-1);
        dummy.next = head;
        while (fast != null){
            fast = fast.next;
            previous = current;
            current = current.next;
        }
        previous.next = current.next;
        current.next = null;
        return dummy.next;
    }
}

No comments:

Post a Comment