leetCode 19.Remove Nth Node From End of List(删除倒数第n个节点) 解题思路和方法
2015-07-06 16:53
751 查看
Remove Nth Node From End of List
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个节点,因为是单链表,不知道节点总数,故先遍历,统计节点总数,算出正数第几个,然后删除即可。
算法很简单,代码如下:
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个节点,因为是单链表,不知道节点总数,故先遍历,统计节点总数,算出正数第几个,然后删除即可。
算法很简单,代码如下:
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ public class Solution { public ListNode removeNthFromEnd(ListNode head, int n) { //删除倒数第n个 if(n == 0){ return head; } int nth = 0;//倒数第n个 int count = 0;//总的节点数 ListNode p = head; //统计count while(p != null){ p = p.next; count++; } //计算正数n的值,从0计算 n = count - n; if(n == 0){//如果为0,说明头结点,返回头结点下一个即可 return head.next; } p = head; //数到n-1,然后令n-1.next = n.next = n-1.next.next即可 while(nth < n - 1){ p = p.next; nth++; } p.next = p.next.next; return head; } }
相关文章推荐
- leetcode Count Complete Tree Nodes
- Umbraco(2) - Creating Your First Template and Content Node(翻译文档)
- [LeetCode] Reverse Nodes in k-Group
- nodejs爬虫系统
- [LeetCode] Swap Nodes in Pairs
- Nodejs和npm学习
- leetcode Populating Next Right Pointers in Each Node 树 队列应用
- 使用DNode实现php和nodejs之间通信的简单实例
- 学习老外用webstorm开发nodejs的技巧--代码提示DefinitelyTyped
- iPhone手机上搭建nodejs服务器步骤方法
- 使用DNode实现php和nodejs之间通信的简单实例
- Hadoop Cluster启动后数据节点(Datanode)进程状态丢失
- Node Glob
- ROS学习手记 - 3 理解ROS中的基本概念_ROS_Nodes
- NodeJS优缺点及适用场景讨论
- sublime快捷方式和node.js
- Nodejs负载均衡:haproxy,slb以及node-slb - i5ting的个人空间 - 开源中国社区
- ovirt-node 之build分析
- LeetCode 之 Populating Next Right Pointers in Each Node I II — C++ 实现
- node.js在前端这个行业中所占的比例