Remove Nth Node From End of List
2015-10-17 14:50
513 查看
class Solution { public: ListNode* removeNthFromEnd(ListNode* head, int n) { if(n<=0||head==NULL) return head; ListNode prehead(0); prehead.next=head; ListNode *p=head; int length=0,i; while(p->next) { length++; p=p->next; } p=&prehead; length++; if(n>length)n=n%length; i=length-n; while(i--)p=p->next; if(n==1) p->next=NULL; else p->next=p->next->next; return prehead.next; } };
效率不高,还是以前的思路,没有创新,下面是别人的一个比较好的
class Solution { public: ListNode* removeNthFromEnd(ListNode* head, int n) { if(n<=0||head==NULL) return head; ListNode prehead(0); prehead.next=head; ListNode *p=&prehead; head=&prehead; while(n--) { p=p->next; } while(p->next) { p=p->next; head=head->next; } head->next=head->next->next; return prehead.next; } };
凡是说倒着第几个都可以利用顺着的第几个打个标记,然后另一个从头开始,这个继续直到这个到结尾。
相关文章推荐
- nodejs支持ssi实现include shtml页面
- <LeetCode><Easy> 19 Remove Nth Node From End of List
- LeetCode解题报告--Swap Nodes in Pairs
- [leetcode] Swap Nodes in Pairs
- assert()断言函数以及NODEBUG用法总结
- hadoop nameNode 无法启动
- 使用 AngularJS & NodeJS 实现基于 token 的认证
- nodejs 计算内存使用率
- Reverse Nodes in k-Group
- 使用node.js的bodyParser中间件读取post数据解析
- Node.js 都应用在什么项目上?这些项目为什么选择 Node.js?
- NodeJS优缺点及适用场景讨论
- 让Node模块在浏览器运行----browserify
- NodeManager启动不起来
- [Cool Node.js] 题记
- Nodejs正则表达式函数之match、test、exec、search、split、replace
- 使用 AngularJS & NodeJS 实现基于 token 的认证应用
- NodeJS、NPM安装配置步骤(windows版本)
- ReactPHP:PHP版的Node.js
- node.js与websocket入门