Remove Nth Node From End of List
Given a linked list, remove the nth node from the end of list and return its head.
Example
Given linked list: 1->2->3->4->5->null, and n = 2.
After removing the second node from the end, the linked list becomes 1->2->3->5->null.
Note
The minimum number of nodes in list is n.
Challenge
O(n) time
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 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 | /** * Definition for ListNode. * public class ListNode { * int val; * ListNode next; * ListNode(int val) { * this.val = val; * this.next = null; * } * } */ 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; } } |