删除链表倒数第n个结点

一次遍历算法

算法

算法可以只使用一次遍历。我们可以使用两个指针而不是一个指针。第一个指针从列表的开头向前移动 n+1 步,而第二个指针将从列表的开头出发。现在,这两个指针被 n 个结点分开。我们通过同时移动两个指针向前来保持这个恒定的间隔,直到第一个指针到达最后一个结点。此时第二个指针将指向从最后一个结点数起的第 n 个结点。我们重新链接第二个指针所引用的结点的 next 指针指向该结点的下下个结点。

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
   
    ListNode first=new ListNode(0);
    ListNode second=new ListNode(0);
    public ListNode removeNthFromEnd(ListNode head, int n) {   
        first.next=head;
        second.next=head;       
        while(n!=0){
            first=first.next;
            n--;
        }
        while(first.next!=null){
            first=first.next;
            second=second.next;
        }
       second.next=second.next.next;
      
        return head;
    }
}

猜你喜欢

转载自www.cnblogs.com/yihangZhou/p/9880167.html