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,
Note:
Given n will always be valid.
Try to do this in one pass.
思路:遍历链表,使用数组保存每个节点的地址。
网上看到的思路,使用两个指针遍历链表,两个指针相距n。对于倒数第n个元素,与其相距n的元素将为空。因此,当第二指针为空时,第一个指针指向的即为要删除的元素。
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; } };
相关文章推荐
- Leetcode-19 Remove Nth Node From End of List
- Remove Nth Node From End of List
- Leetcode 19. Remove Nth Node From End of List
- LeetCode 19. Remove Nth Node From End of List
- 19. Remove Nth Node From End of List
- Remove Nth Node From End of List ---LeetCode
- LeetCode41/19 First Missing Positive/Remove Nth Node From End of List ****
- leetcode 019 Remove Nth Node From End of List (Python)
- LeetCode之Remove Nth Node From End of List
- Remove Nth Node From End of List
- LeetCode 19.Remove Nth Node From End of List
- LeetCode 19 : Remove Nth Node From End of List (Java)
- leetcode: Remove Nth Node From End of List
- leetcode 19. Remove Nth Node From End of List
- 19. Remove Nth Node From End of List
- Remove Nth Node From End of List
- [leetcode]Remove Nth Node From End of List
- LeetCode Remove Nth Node From End of List
- Remove Nth Node From End of List
- LeetCode #19 Remove Nth Node From End of List (E)