Joey LIU | NANTSOU


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode former = head;
        ListNode latter = head;
        while (n-- > 0) {
            former = former.next;
        }
        if (former == null) {
            return head.next;
        }
        while (former.next != null) {
            former = former.next;
            latter = latter.next;
        }
        latter.next = latter.next.next;
        return head;
    }
}