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

Remove Nth Node From End of List

2014-09-06 15:36 260 查看
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.

思路:遍历链表,使用数组保存每个节点的地址。

class Solution {
public:
ListNode *removeNthFromEnd( ListNode *head, int n ) {
if( !head ) { return 0; }
vector<ListNode*> nodeVec;
int size = 0;
while( head ) {
nodeVec.push_back( head );
head = head->next;
++size;
}
if( size-n == 0 ) { return nodeVec[0]->next; }
nodeVec[size-n-1]->next = nodeVec[size-n]->next;
return nodeVec[0];
}
};


网上看到的思路,使用两个指针遍历链表,两个指针相距n。对于倒数第n个元素,与其相距n的元素将为空。因此,当第二指针为空时,第一个指针指向的即为要删除的元素。

class Solution {
public:
ListNode *removeNthFromEnd( ListNode *head, int n ) {
ListNode guard(-1);
guard.next = head;
head = &guard;
for( int i = 0; i < n; ++i ) { head = head->next; }
ListNode *node = &guard;
while( head->next ) {
node = node->next;
head = head->next;
}
node->next = node->next->next;
return guard.next;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: