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

【LeetCode】Remove Nth Node From End of List

2014-06-07 13:54 309 查看
题目介绍:

题目的关键点在于,要求只遍历链表一次

下面给出两种算法:

算法一利用额外空间,先将链表数都取出放到数组中,再重组链表,此时删除指定项;

<span style="font-family:Times New Roman;font-size:14px;">ListNode *removeNthFromEnd(ListNode *head, int n) {
vector<int> arr;
ListNode *cur = head;
ListNode *headNew = NULL;
while (cur)
{
arr.push_back(cur->val);
cur = cur->next;
}
int size = arr.size();
cur = NULL;
bool isHead = true;
for (int i = 0; i < size; i++) {
if (i != size - n) {
if (isHead) {
headNew = new ListNode(arr[i]);
isHead = false;
cur = headNew;
}
else {
cur->next = new ListNode(arr[i]);
cur = cur->next;
}
}
}
return headNew;
}</span>


算法二则通过两个指针来确定所需删除的项,然后对其进行删除:

<span style="font-family:Times New Roman;font-size:14px;">ListNode *removeNthFromEnd2(ListNode *head, int n) {
if (head == NULL)
return NULL;
// 在列表头加一个头指针,并将searchPtr和locatePtr指向它
ListNode pre(0); pre.next = head;
ListNode *searchPtr = &pre, *locatePtr =  ⪯
// 先将searchPtr预先移动n个位置
while (n--) {
searchPtr = searchPtr->next;
}
// 然后同步移动searchPtr和locatePtr指针,则当searchPtr到头时,locatePtr正好可以指向要删除数字的前一个位置
while (searchPtr != NULL && searchPtr->next != NULL) {
searchPtr = searchPtr->next;
locatePtr = locatePtr->next;
}
// 直接删除所在位置既可
locatePtr->next = locatePtr->next->next;
return pre.next;
}</span>


这里实际上有两个指针在遍历链表,所以是否算是一次遍历有待商榷,仅供参考。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: