首页 > 其他 > 详细

【LeetCode】Remove Nth Node From End of List (2 solutions)

时间:2014-11-06 21:46:25      阅读:311      评论:0      收藏:0      [点我收藏+]

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.

 

这题的难点在于one pass

没到尾部就没法进行倒退n个节点的操作。

但是到达尾部之后,再进行倒退删除操作,就不满足one pass了

由此诞生解法一:使用数组记录所有节点的位置,通过下标计算(尾节点位置-n+1)立刻定位到需要删除的节点了

建立vector存放ListNode*,每个指针指向一个链表节点

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution 
{
public:
    ListNode *removeNthFromEnd(ListNode *head, int n) 
    {
        vector<ListNode*> v;
        ListNode* cur = head;
        while(cur != NULL)
        {
            ListNode* p = cur;
            v.push_back(p);
            cur = cur->next;
        }
        int size = v.size();
        int num = size-n;
        if(num == 0)//first, no pre
            return head->next;
        else if(num == size-1)//last but not first, no post
        {
            v[num-1]->next = NULL;
            return head;
        }
        else    //pre link to post
        {
            v[num-1]->next = v[num+1];
            return head;
        }
    }
};

bubuko.com,布布扣

 

仔细分析之后觉得浪费空间太多。

我们只是通过尾节点位置确定需要删除节点(n-1个偏移量),不需要其他的位置信息。

只需要两个位置相差n-1的指针,当前面的指针指向尾节点时,后面的节点即指向需要删除的节点。

由此产生解法二:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution 
{
public:
    ListNode *removeNthFromEnd(ListNode *head, int n) 
    {
        ListNode* fast = head;  //the node at the last node
        ListNode* preslow = NULL;
        ListNode* slow = head;  //the node to delete
        
        int i = 1;
        while(i < n)
        {
            fast = fast->next;
            i ++;
        }
        
        while(fast->next != NULL)
        {
            fast = fast->next;
            preslow = slow;
            slow = slow->next;
        }
        //fast at the last node, slow at the node to delete
        
        if(preslow == NULL)
        //delete the head
            return head->next;
        else
        {
            preslow->next = slow->next;
            return head;
        }
    }
};

bubuko.com,布布扣

 

【LeetCode】Remove Nth Node From End of List (2 solutions)

原文:http://www.cnblogs.com/ganganloveu/p/4079879.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!