菜单 学习猿地 - LMONKEY

VIP

开通学习猿地VIP

尊享10项VIP特权 持续新增

知识通关挑战

打卡带练!告别无效练习

接私单赚外块

VIP优先接,累计金额超百万

学习猿地私房课免费学

大厂实战课仅对VIP开放

你的一对一导师

每月可免费咨询大牛30次

领取更多软件工程师实用特权

入驻
197
0

leetcode第19题--Remove Nth Node From End of List

原创
05/13 14:22
阅读数 91311

Problem:

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.

果然一次就通过了。先读到尾,知道长度后,再从头开始读到要去掉的前一位,然后把要去掉的next复制给要去掉的前一个的next就可以。

/**
 * 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)
{
    int len = 1;
    ListNode *tmp = head;
    while(tmp -> next != NULL)
    {
        len++;
        tmp = tmp -> next;
    }
    if (len == n)
        return head -> next;
    ListNode *p = head;
    for(int i = 1; i < len - n; i++)
    {
        p = p -> next;
    }
    p -> next = p -> next -> next;
    return head;
}
};

 但是要挑战只遍历一次就通过就不能这样了。如下给了解法

http://blog.csdn.net/havenoidea/article/details/12918561

由于链表是单向的,不能倒着搜索,因此设置两个指针,他们相隔n个节点的距离,同布移动。

当前面的指针到达链表结尾的时候,后面一个指针离结尾的距离正好是n,再删除要求的节点就ok了。

要注意的我觉得应该有两点:

第一如果链表不到n个节点,就没有删除的元素,判断一下防止非法访问内存(后来发现题目说了没有这个情况,随意了就当作代码严谨一点吧)。

第二不好删除当前访问的节点,特别是删除的头节点就比较麻烦了。所以增加一个节点链接头节点,这样间隔距离多一步,就能容易地删除下一个节点了。

/**
 * 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 *left,*right,*Head;
        right=head;
        for(int i=0;i<n;++i)
        {
            if(!right)return head;
            right=right->next;
        }
        Head=left=new ListNode(-1);
        Head->next=head;
        while(right)
        {
            right=right->next;
            left=left->next;
        }
        ListNode *t1=left->next,*t2;
        if(t1)left->next=left->next->next;
        delete(t1);
        t2=Head->next;
        delete(Head);
        return t2;
    }
};
// blog.csdn.net/havenoidea

 

发表评论

0/200
197 点赞
0 评论
收藏