LeetCode 19. 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.

给一个链表,删除倒数第n个数字,我们的策略是两个指针,从头开始,假设倒数第五个,先让一个指针走出去五个,然后两个同时启动,当第一个到了最末尾,第二个也就到了我们最终想要的位置了。

java代码:

public static ListNode removeNthFromEnd(ListNode head, int n) {

        if (n < 1) return head;
        int i = 0;
        ListNode before = head;
        while (i < n + 1 && before != null) {
            before = before.next;
            i++;
        }
        if(i == n+1){
            ListNode after = head;
            while(before!=null){
                before = before.next;
                after = after.next;
            }
            ListNode temp = after.next;
            after.next = temp.next;
        }else if (i == n){
            ListNode tmep = head;
            head = head.next;
        }
        return head;
    }

推荐阅读更多精彩内容