LeetCode题解: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个结点,返回新链表的头部

解决思路:

  1. 倒数第n个结点相当于顺数第N-n+1个结点(N为链表长度),那我们只要让顺数第N-n个结点指向后面的结点就可以了。

  2. 先用一个指针移动到第N-n个结点的位置,然后用另一个指针指向链表头部,两个指针再同时移动,当第一个结点为空时,另一个结点就指向要被删除结点的前一个结点了

代码:

public class Solution {
    public ListNode removeNthFromEnd(ListNode head, int n) {
    ListNode start = new ListNode(0);
    ListNode slow = start;
    ListNode fast = start;

    slow.next = head;

    for(int i=0; i< n + 1; i++)   {
        fast = fast.next;
    }

    while(fast != null) {
        slow = slow.next;
        fast = fast.next;
    }

    slow.next = slow.next.next;

    return start.next;
    }
}

你可能感兴趣的:(LeetCode题解:Remove Nth Node From End of List)