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.

分析:乍一看,这还不简单么,遍历一遍链表,记下其长度len,然后再遍历找到len-n节点,删之。但是,题目要求只能遍历一遍!!遍历两遍是违规的!!

但是如何做到仅遍历一遍,又能知道当前遍历项是倒数第几位呢?答案是递归。

当访问到最后一个节点时,便知道它是倒数第一个了,即n = 1。
这时我只需返回1给上层调用函数使用即可

因为删除第n个节点需要要第n+1个节点的引用,以便

node.next = node.next.next

但是对于第一个节点而言,其父节点为null,我们自然不能使用上述语句,于是一定要记得为其做特殊处理。

代码:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        if (remove(head, n) > 0) {
            return head.next;   
        }

        return head;
    }

    private int remove(ListNode node, int n) {
        if (node.next == null) return 1;
        int rank;
        rank = remove(node.next, n) + 1;

        // the way to delete the nth node
        // is to set the (n-1)th node's next
        // as nth node's next
        // [tricky] return a very big negtive number
        // to indicate we are success
        if (rank == n + 1) {
            node.next = node.next.next;
            return Integer.MIN_VALUE;
        }
        return rank;
    }
}

ssnau
1.5k 声望98 粉丝

负能量职业打码师


引用和评论

0 条评论