19. Remove Nth Node From End of List
2016-04-26 09:35
585 查看
class Solution { public: ListNode* removeNthFromEnd(ListNode* head, int n) { ListNode *temp=head; int count=0; while(temp) { count++; temp=temp->next; } int del=count-n+1; ListNode *prenode=new ListNode(-1); ListNode *pre=prenode; pre->next=head; temp=head; count=1; while(temp) { if (count == del) { pre->next = pre->next->next; break; } pre=temp; temp=temp->next; count++; } return prenode->next; } };
这是第二种解决方法 整个过程只需要遍历一遍 当后指针指向n+2个节点的时候 前指针指向第一个数 当后指针为null的时候 前指针指向倒数第n个节点的前驱节点。
class Solution { public: ListNode* removeNthFromEnd(ListNode* head, int n) { if(!head) return head; ListNode *prehead=new ListNode(-1); if(!head->next&&n==1) return NULL; prehead->next=head; ListNode *first=NULL; ListNode *tail=prehead; int count=1; while(tail) { if(count==n+2) { first=prehead; } tail=tail->next; count++; if(first) first=first->next; } if(count==n+2) { first=prehead; } first->next=first->next->next; return prehead->next; } };
相关文章推荐
- Windows 系统下设置Nodejs NPM全局路径
- Nodejs笔记(三)
- leetcode-24. Swap Nodes in Pairs
- nodejs原理
- Hadoop学习(三)— hdfs : NameNode与DataNode的实现机制
- LeetCode------Delete Node in a Linked List
- nodejs完整登陆交互
- LeeCode-Swap Nodes in Pairs
- LeeCode-Delete Node in a Linked List
- 解决NameNode配置HA后Hive路径不正确的问题
- node.js 模板 ejs
- 利用Node.js流和事件处理文本文件
- node.js cluster多进程、负载均衡和平滑重启
- web编程速度大比拼(nodejs go python)(非专业对比)
- Ajax跨域问题的解决方法之一 —— "Access-Control-Allow-Origin"
- 菜鸟学习nodejs--express(二)路由
- node.js---sails项目开发(2)
- node.js WebService异常处理(domain)以及利用domain实现request生命周期的全局变量
- node.js---sails项目开发(1)
- nodejs学习一CommonJS和AMD