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

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