• Leetcode.19 Remove Nth Node From End of List


    问题描述:

    Given a linked list, remove the n-th node from the end of list and return its head.

    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.

    Follow up:

    Could you do this in one pass?

    我的思路:

    一开始想的方法类似于暴力破解方法,即对每一个节点,判断它是否为目标节点,但是这样的时间复杂度较高为O(mn), m为链表长度,n为参数中的n,然后就想让时间复杂度低一点,能否遍历一遍就能找到位置并删除。

    我的想法是这样的,用了三个指针p, prev, del,和一个count计数变量,一个指针p遍历链表,当距离达到n时移动del(为我们想要删除的指针),当移动一次del后移动prev(指向要删除的指针的指针)

    这样当跳出循环的时候我们需要判定count是否为0,若count为0,则表明del是我们想要删除的位置,若count不为0,则不存在我们想要删除的节点,不过,问题中说n永远有效,可以不考虑这一点。

    除此之外,还应考虑要删除的节点为头节点怎么办,这时可直接返回head->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) {
            if(!head || n == 0)
                return head;
            ListNode *p = head, *prev = head, *del = head;
            int count = n;
            while(p){
                p = p->next;
                if(del != head)
                    prev = prev->next;
                if(count == 0){
                    del = del->next;
                }else{
                    count--;
                }
            }
            if(count){
               return head; 
            }
            if(del == head)
                return head->next;
            prev->next = del->next;
            return head;
        }
    };

    运行时间为13ms,只达到了14.05%的标准

    改进:

    看了http://www.cnblogs.com/grandyang/p/4606920.html的解法并试了一下,运行时间10ms,并且击败了75.29%

  • 相关阅读:
    iOS 动画总结UIView动画
    iPhone 本地通知
    NSNotification学习笔记
    [重构]把程序写得更简洁,更好维护
    使用asp:Timer控件为站点创建一个实时时钟
    为用户控件(UserControl)写属性
    Gridview前面10行数据显示背景色
    MS SQL获取最大值或最小值日期的函数
    How to modify Inventory Aging Report form days field default value
    DropDownlist的DataTextField显示多列数据
  • 原文地址:https://www.cnblogs.com/yaoyudadudu/p/9070246.html
Copyright © 2020-2023  润新知