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.


分析

1 典型的快慢指针的题

2 需要注意的是要先构造一个dummy来存放ListNode(0),作为头结点的头结点

   为的是处理头结点被删掉的情形

3 做题时用while循环在很多时候比用for循环思路更清晰


代码

public ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        ListNode firstNode = dummy;
        while (n > 0){
            firstNode = firstNode.next;
            n--;
        }
        ListNode secondNode  = dummy;
        while (firstNode.next!= null){
            secondNode = secondNode.next;
            firstNode = firstNode.next;
        }
        secondNode.next = secondNode.next.next;
        return dummy.next;    
    }


猜你喜欢

转载自blog.csdn.net/vvnnnn/article/details/80077569