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%

原文地址:https://www.cnblogs.com/yaoyudadudu/p/9070246.html