Leetcode(16) - Remove Nth Node From End of List
2017-06-15 11:16
405 查看
https://leetcode.com/problems/remove-nth-node-from-end-of-list/#/description
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.
Solution:
用两个指针来处理问题,一个指针先移动n位,一个指针指向Head,然后一起移动,当前指针为空时,删除后指针指向的Node。
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.
Solution:
用两个指针来处理问题,一个指针先移动n位,一个指针指向Head,然后一起移动,当前指针为空时,删除后指针指向的Node。
ListNode* RemoveNthFromEnd::removeNthFromEnd(ListNode *head, int n) { if(head == nullptr || n == 0) { return nullptr; } ListNode* pAhead = head; for(unsigned int i = 0; i < n - 1; ++i) { if(pAhead ->m_pNext != nullptr) { pAhead = pAhead -> m_pNext; } else { return head; } } ListNode** pBehind = &head; while (pAhead -> m_pNext != nullptr) { pAhead = pAhead -> m_pNext; pBehind = &((*pBehind) -> m_pNext); } *pBehind = (*pBehind) -> m_pNext; return head; }
相关文章推荐
- leetcode -- Remove Nth Node From End of List
- [Leetcode] Remove Nth Node From End of List
- LeetCode 19: Remove Nth Node From End of List
- LeetCode: Remove Nth Node From End of List
- LeetCode - Remove Nth Node From End of List
- [LeetCode] Remove Nth Node From End of List
- [LeetCode] Remove Nth Node From End of List 解题报告
- leetcode 40: Remove Nth Node From End of List
- [LeetCode] Remove Nth Node From End of List
- [LeetCode] Remove Nth Node From End of List
- [Leetcode 19] 19 Remove Nth Node From End Of List
- LeetCode-Remove Nth Node From End of List
- leetcode 40: Remove Nth Node From End of List
- [Leetcode] Remove Nth Node From End of List
- [leetcode]Remove Nth Node From End of List
- LeetCode: Remove Nth Node From End of List
- [leetcode刷题系列]Remove Nth Node From End of List
- leetcode--Remove Nth Node From End of List
- LeetCode-Remove Nth Node From End of List
- LeetCode: Remove Nth Node From End of List