Leetcode(19) 删除链表的倒数第N个节点

182 阅读1分钟

Remove Nth Node From End of List(19)

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?

关键技巧,快慢指针:

 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public static ListNode removeNthFromEnd(ListNode head, int n) { //head 1-2-3-4-5
        if (head == null || n <= 0) {
            return head;
        }
        ListNode guide = new ListNode(-1);
        guide.next = head;
        ListNode first = guide;
        ListNode second = guide;

        for (int i = 0; i < n; i++) {
            if (first != null) {
                first = first.next;      //1-2-3-4-5  //2-3-4-5 //3-4-5  //4-5
            }
        }
        while (first != null && first.next != null){
            first = first.next;
            second = second.next;
        }
        second.next = second.next.next;
        return guide.next;

    }
}