2015年4月28日星期二

Remove Nth Node From End of List leetcode

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.

首先先让faster从起始点往后跑n步。
然后再让slower和faster一起跑,直到faster==null时候,slower所指向的node就是需要删除的节点。
注意:慢指针要在dummy上而不是head上 因为可能head位的数值被删除
return也要return dummy.next 因为head可能被删除

时间O(n) 空间O(1)

public class Solution {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        if (n <= 0){
            return null;
        }
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        ListNode faster = head;
        ListNode slower = dummy;
        for (int i = 0; i < n; i++){
            if (faster == null){
                return null;
            }
            faster = faster.next;
        }
        while (faster!= null){
            faster = faster.next;
            slower = slower.next;
        }
        slower.next = slower.next.next;
        return dummy.next;
        
    }
}

没有评论:

发表评论