您的位置:首页 > Web前端 > Node.js

leetcode 19:Remove Nth Node From End of List(15-10-7)

2015-10-08 20:25 741 查看
一.题目

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.

链表结点定义如下:

* struct ListNode {
*     int val;
*     ListNode *next;
*     ListNode(int x) : val(x), next(NULL) {}
* };


二.思路
目前有两种思路:

第一种是先遍历一遍链表,得到链表长度N,然后再从头开始遍历N-n-1次,得到删除结点的前一个结点,总时间为O(2*N-n)也算是O(N)么?

另一种是先遍历一遍链表,然后定义一个结点数组,存下结点,这样得到N后就不许遍历,直接可以访问删除结点的前一个结点,总时间为O(N),只是要牺牲大量的内存空间,所以还是第一种方法好。

三.实现

#include<iostream>

using namespace std;

struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};

class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode *p = head;
int size = 0;
for (; p != NULL; p = p->next) size++;
p = head;
if (size == 1) return NULL;                          //A
if (size == n)                                       //B
{
head = head->next;
delete p;
return head;
}
for (int i = 1; i < size - n; i++) p = p->next;
ListNode *q = p->next;
p->next = q->next;
delete q;
return head;
}
};

int main()
{
ListNode *a = new ListNode(1);
ListNode *b = new ListNode(2);
ListNode *c = new ListNode(3);
ListNode *d = new ListNode(4);
ListNode *e = new ListNode(5);
a->next = b;
b->next = c;
c->next = d;
d->next = e;
Solution s;
ListNode *head = s.removeNthFromEnd(a,5);
for (; head != NULL; head = head->next)
cout << head->val << " ";
cout << endl;
}


注意:A B两个边界条件

下面是网友的比较好的一种方法:

先遍历n次,然后后面再遍历N-n次,后面遍历时,两个指针同时进行。

ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode* ans;
ListNode* slow = head; //t1
ListNode* fast = head; //t2

for(int i=0;i<n;++i)
{
fast = fast->next;
}

if(fast == NULL)
{
ans = head->next;
delete head;
return ans;
}

while(fast->next != NULL)
{
fast = fast->next;
slow = slow->next;
}
delete slow->next;
slow->next = slow->next->next;

return head;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: