您的位置:首页 > Web前端 > Node.js

remove-nth-node-from-end-of-list

2015-06-11 19:56 543 查看


容易 删除链表中倒数第n个节点

30%

通过

给定一个链表,删除链表中倒数第n个节点,返回链表的头节点。

您在真实的面试中是否遇到过这个题?

Yes

样例

给出链表1->2->3->4->5->null和 n = 2.
删除倒数第二个节点之后,这个链表将变成1->2->3->5->null.

注意

链表中的节点个数大于等于n

挑战

O(n)时间复杂度
搞半天,两个指针,一个head,一个tail,head走到尾的时候,tail正好走到n+1..
/**
 * Definition for ListNode.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int val) {
 *         this.val = val;
 *         this.next = null;
 *     }
 * }
 */ 
public class Solution {
    /**
     * @param head: The first node of linked list.
     * @param n: An integer.
     * @return: The head of linked list.
     */
    ListNode removeNthFromEnd(ListNode head, int n) {
        if (0 == n) {
            return head;
        }
        if (head.next == null) {
            return null;
        }
        ListNode p = head;
        ListNode q = head;
        while (n != 0) {
            q = q.next;
            n--;
            /*
             * if n equals to the number of nodes, that means remove the first node, so just let the head to be the head.next.
             */
            // 处理n没有走完的情况,说明链表的长度肯定是<=n,所以移除head
            if (q.next == null && n != 0) {
                head = head.next;
                return head;
            }
        }
        // 处理p后移的问题,保证p和q之间有n个节点,这样移除p之后的一个节点即可
        while (q.next != null) {
            q = q.next;
            p = p.next;
        }
        // 处理移除末尾节点
        if (n == 1) {
            p.next = null;
            return head;
        } else {
            p.next = p.next.next;
            return head;
        }
        }
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: