Leetcode: Remove Nth Node From End of List
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.
这道题要注意的Corner Case是:如果n比这个LinkedList的size大,那么就需要直接返回Head,如果相等,就把head删掉,返回head.next;基本做的方法呢,还是Runner Technique. 由于有可能head会被删掉,所以最好还是使用一个dummy node,dummy.next = head。
1 /** 2 * Definition for singly-linked list. 3 * public class ListNode { 4 * int val; 5 * ListNode next; 6 * ListNode(int x) { val = x; } 7 * } 8 */ 9 class Solution { 10 public ListNode removeNthFromEnd(ListNode head, int n) { 11 ListNode dummy = new ListNode(-1); 12 dummy.next = head; 13 ListNode p1 = dummy, p2 = dummy; 14 while (p2.next != null) { 15 if (n > 0) { 16 n --; 17 } 18 else p1 = p1.next; 19 p2 = p2.next; 20 } 21 if (n == 0) p1.next = p1.next.next; 22 return dummy.next; 23 } 24 }