Shawngbk / Leecode

Questions of Leecode
0 stars 0 forks source link

19. Remove Nth Node From End of List #2

Open Shawngbk opened 7 years ago

Shawngbk commented 7 years ago

思路:题目说 one pass。。。 那么,这样,用两个直指针。p,q p先跑n步,然后q和p一起跑,那么p跑到最后,q就正好在倒数第n个上面了 subs是新建的head 免去了单独处理原来head的麻烦 public class Solution { public ListNode removeNthFromEnd(ListNode head, int n) { ListNode subs = new ListNode(0); subs.next = head; ListNode p = subs; ListNode q = subs; for(int i=0; i<n; i++) { p = p.next; }

    while(p.next != null) {
        p = p.next;
        q = q.next;
    }
    q.next = q.next.next;
    return subs.next;
}

}