leetcode-19 Remove Nth Node From End of List
2016-03-25 16:47
471 查看
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.
思路:两个指针,其中一个指针先走n步
//////////////////////////////////////////////////////////////////////////
// start: remove the nth node from the end of list
ListNode *removeNthFromEnd(ListNode *head, int n)
{
if(n <= 0 || !head)
return head;
ListNode *ahead = head, *behind = head;
for(int i = 0; i < n; i++)
ahead = ahead->next; // ahead n
while(ahead->next)
{
ahead = ahead->next;
behind = behind->next;
}
// delete node behind->next
ListNode *tmp = behind->next;
behind->next = p->next->next;
delete tmp;
return head;
}
// end
//////////////////////////////////////////////////////////////////////////
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.
思路:两个指针,其中一个指针先走n步
//////////////////////////////////////////////////////////////////////////
// start: remove the nth node from the end of list
ListNode *removeNthFromEnd(ListNode *head, int n)
{
if(n <= 0 || !head)
return head;
ListNode *ahead = head, *behind = head;
for(int i = 0; i < n; i++)
ahead = ahead->next; // ahead n
while(ahead->next)
{
ahead = ahead->next;
behind = behind->next;
}
// delete node behind->next
ListNode *tmp = behind->next;
behind->next = p->next->next;
delete tmp;
return head;
}
// end
//////////////////////////////////////////////////////////////////////////
相关文章推荐
- 进程与线程。js是什么运行机制?node.js是什么运行机制?
- DataNode启动失败解决
- Namenode HA
- nodejs nodejs模块使用及简单的示例
- 初学node.js
- 初学nodejs
- leetcode 25. Reverse Nodes in k-Group
- leetcode 24. Swap Nodes in Pairs
- nodejs笔记三--url处理、Query String;
- nodejs笔记二--文件I/O;
- leetcode @python 117. Populating Next Right Pointers in Each Node II.py
- nodejs笔记一--模块,全局process对象;
- Node.js的expressjs框架对response的处理流程实验
- leetcode @python 116. Populating Next Right Pointers in Each Node
- node.js学习笔记(3)--Express创建的项目分析
- mysql node
- 进程与线程。js是什么运行机制?node.js是什么运行机制?
- 237. Delete Node in a Linked List
- 初了解NodeJS
- Node.js基础学习之常见API理解