Leetcode: Remove Nth Node From End of List

来源:互联网 发布:江苏省人工智能会议 编辑:程序博客网 时间:2024/05/16 19:49

Problem:

Given a linked list, remove the nth node from the end of list and return its head.

For example,

   Given linked list: 1->2->3->4->5, and n = 2.   After removing the second node from the end, the linked list becomes 1->2->3->5.

Note:
Given n will always be valid.
Try to do this in one pass.




Solution:


Main Idea:

n + length - n = length;

So if we have to pointers, p1 and p2.  all are in front of the head;

Then if we, let the first pointer p1 move right n steps.  Then it has length - n steps to reach the end.

So if then we let the p1 and p2 all move right.  When p1 reaches the end, p2 will also have moved length - n steps.  So p2 has  n steps to go to reach the end.  So we can find the node we want using p2. 

/** * Definition for singly-linked list. * public class ListNode { *     int val; *     ListNode next; *     ListNode(int x) { *         val = x; *         next = null; *     } * } */public class Solution {    public ListNode removeNthFromEnd(ListNode head, int n) {                if (head == null || n == 0) {            return head;        }        ListNode newHead = new ListNode(0);        newHead.next = head;        ListNode p1 = newHead;        ListNode p2 = newHead;        while (p1.next != null && n > 0) {            p1 = p1.next;            n--;        }        if (n != 0) return head;                while (p1.next != null) {            p1 = p1.next;            p2 = p2.next;        }                if (p2.next.next == null) {            p2.next = null;                    } else {            ListNode next = p2.next.next;            p2.next = next;                    }                return newHead.next;    }}


0 0