19. Remove Nth Node From End of List (双指针)

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

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.

Follow up:

Could you do this in one pass?

分析:

要在一遍内执行完的问题就是指针不能知道当前节点是倒数第几个,所以考虑用快慢指针。快指针比慢指针快n个节点,当快指针的下一个元素为空就说明慢指针的下一个节点应该删除。

注意:

1. 如果链表本来就只有一个节点,删除之后就是空,所以不能返回head,而是应该new一个新的节点指向head,返回新节点的next;

 public ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode sta = new ListNode(0);
        ListNode slow = sta;
        ListNode fast = sta;
        slow.next = head;
        for(int i=0;i<n;i++)
            fast = fast.next;
        while(fast.next!=null){
            fast = fast.next;
            slow = slow.next;
        }
        slow.next = slow.next.next;
        return sta.next;
    }

猜你喜欢

转载自blog.csdn.net/shulixu/article/details/86236845