LeetCode:Remove Nth Node From End of List
2015-07-16 15:55
627 查看
problem:
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.
Solution:解决方式采用双指针,前后指针相差n
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.
Solution:解决方式采用双指针,前后指针相差n
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode* removeNthFromEnd(ListNode* head, int n) { //题意是要删除从最后一个节点往前数的第n个节点 考虑到只有一个节点时没有办法删除 加一个dummy ListNode *dummy=new ListNode(-1); dummy->next=head; ListNode *pre=dummy; ListNode *last=dummy; //找到last的初始位置 while(n--) { last=last->next; } while(last->next!=NULL) { pre=pre->next; last=last->next; } //删除节点 ListNode *object=pre->next; pre->next=pre->next->next; delete object; return dummy->next; } };
相关文章推荐
- nodejs pm2 介绍
- Delete Node in a Linked List
- 初学NodeJs:
- 【leetcode】Delete Node in a Linked List
- leetcode-237-Delete Node in a Linked List
- LeetCode:Delete Node in a Linked List
- Error: unable to connect to node 'rabbit@devlop-ceilo': nodedown
- Delete Node in a Linked List
- nodejs安装遇到的问题
- 用NodeJS搭建一个内容管理系统(v0.0.1)
- hadoop的namenode无法启动的解决办法
- 开启Node.js的大门
- LeetCode从零单排之零分段——Delete Node in a Linked List(删除链表中的元素)
- 和阿木聊Node.js
- [LeetCode][JavaScript]Delete Node in a Linked List
- LeetCode Delete Node in a Linked List
- nodejs express3.x 与 express4.x 的router区别 与修改方法
- Ubuntu 14.04下hadoop 2.2.0 伪分布环境配置datanode不能启动的解决办法
- 【排错】Failed to replace a bad datanode on the existing pipeline due to no more good ...
- 用MindNode描述了一个小项目思路