19. Remove Nth Node From End of List 倒数删除链表元素

思路:第一时间想到的肯定是通过添加计数器解决这个问题,但是问题产生了,链表具有单向性,统计总数,还是计算当前数目都在效率上面很吃亏。

借用快慢指针的思想。可以安排两个同速指针,但是他们存在先后顺序,就可以解决这个问题。

public class Solution {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        if(head == null || n <= 0) return null;
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        ListNode pre = dummy;
        ListNode index = dummy.next;
        int count = n;
        while(count > 0)
        {
            index = index.next;
            count--;
        }
        while(index != null)
        {
            index = index.next;
            pre = pre.next;
        }
        pre.next =  pre.next.next;
        return dummy.next;
    }
}

 

posted @ 2016-04-23 09:38  ProWhalen  阅读(132)  评论(0)    收藏  举报