Remove Nth Node From End of List
来源:互联网 发布:linux压缩成tar.gz 编辑:程序博客网 时间:2024/04/30 11:36
难度:1
删除链表里倒数第n个节点
据说标准算法是两个指针,同时向右扫,相差n-1,当后面的没有后继时就找到了倒数第n个节点
我的算法很简单,从左到右扫一遍,记录个数num,再从头到尾移动num-n次,就找到该节点
题目说尽量只扫一次,我扫了两次,
但是如果我刚才说的标准算法真的是标准算法的话,
会分析复杂度的同学都知道两者的时间复杂度一样的,我的方法相比标准算法更简单明了(一切的前提是那个标准算法真的是标准算法的前提下)
我做了比较,
我的方法是36MS,所谓的标准算法是40MS,时间差不多,如果有更好的方法,请联系我!
class Solution {public: ListNode *removeNthFromEnd(ListNode *head, int n) { ListNode *p=head; int num=0; while(p) { num++; p=p->next; } if(num == n) { ListNode *ans=head->next; free(head); return ans; } num-=n; p=head; for(int i=0;i<num-1;i++) { p=p->next; } ListNode *tmp=p->next; p->next=p->next->next; free(tmp); return head; }};
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node from End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- HibernateDaoSupport 和 JdbcDaoSupport 的封装
- North Face UK The $2 billion deal works out to $43 per Timberland share
- 远程复制文件 xcopy
- 我的Android进阶之旅------>WindowManager.LayoutParams介绍
- 网页编码和java编码的一些东西
- Remove Nth Node From End of List
- 财务分析与决策-习题纠缠
- mini2440裸机编程------IIS
- 各国程序员的差异
- 39级台阶
- Leetcode: Two Sum
- LA 3211 Now or Later
- 芒格在斯坦福学院的演讲:生活智慧
- a+=1/a=+1/a-=1区别-c语言