zoukankan      html  css  js  c++  java
  • leetcode第19题--Remove Nth Node From End of List

    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
  • 相关阅读:
    三个心态做人做学问 沧海
    成功走职场要找准自己的"快捷键" 沧海
    免费离线下载 拂晓风起
    Hibernate 获取某个表全部记录时 奇怪现象 (重复出现某个记录) 拂晓风起
    无法读取mdb 如果连接不了ACCESS mdb文件,就尝试安装MDAC 拂晓风起
    Netbeans 使用 Hibernate 逆向工程 生成hbm和pojo 拂晓风起
    如何点击单选框 radio 后面的文字,选中单选框 拂晓风起
    Java 连接access 使用access文件 不用配置 拂晓风起
    mysql下如何执行sql脚本 拂晓风起
    Hibernate配置access Hibernate 连接 access 拂晓风起
  • 原文地址:https://www.cnblogs.com/higerzhang/p/4034061.html
Copyright © 2011-2022 走看看