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

LeetCode之19---Remove Nth Node From End of List

2016-04-16 14:33 531 查看


题目:

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.


题目大意:

  给定一个链表和整数n,要求删除从链表的最后一个开始向前第n个结点,返回删除后的链表。

思路:

  由题目可以很容易的看出规律:从后向前的第n个结点实际上是从前向后的第链表长度 - n 个结点,所以只需要计算出链表的长度,然后计算出从前向后的结点位置,再删除就可以了。从基本思路可以看出这里需要扫描两次链表,一次是计算链表长度,另一次是寻找删除位置。可是。。。两次遍历有重复部分。所以我们可以用一个数组来存储所有结点的地址,并且以下标作为结点的位置,这样在确定删除的目标位置时就不用再次扫描链表,但是这样做的缺点也显而易见---浪费了内存。

代码:

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

class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode *pTemp = head;
ListNode *hash[1000] = {nullptr};
int len = 0;

while (pTemp) {
hash[len] = pTemp;
pTemp = pTemp->next;
++len;
}

int tar = len - n;

delete(hash[tar]);

if (tar == 0) {
head = hash[tar + 1];
} else {
hash[tar - 1]->next = hash[tar + 1];
}

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