LeetCode Remove Nth Node From End of List(019)解法总结

398 阅读1分钟

描述

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?

思路

使用两个指针避免回溯的情况,只需要让两个指针保持N的距离即可。

要注意链表长度为N时的特殊情况,即应当直接返回去除头结点链表的情况。

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        //定义两个节点
        ListNode fir = head, sec = null;
        
        //将两个节点距离拉开,其中if判断N为链表长度的特殊情况
        for(int i = 0; i<n+1; i++){
            if(fir == null){
                return head.next;
            }
            fir = fir.next;
        }
        //非特殊情况下第二个指针的初始化
        sec = head;
        //两个指针保持距离移动
        while(fir != null){
            fir = fir.next;
            sec = sec.next;
        }
        //进行删除节点操作
        sec.next = sec.next.next;
        return head;
    }
}
Runtime: 0 ms, faster than 100.00% of Java online submissions for Remove Nth Node From End of List.
Memory Usage: 38.1 MB, less than 6.37% of Java online submissions for Remove Nth Node From End of List.

只进行一次遍历可以减小很多时间消耗,而代价只是一个O(1)的空间消耗。