19. Remove Nth Node From End of List
2016-03-15 16:01
295 查看
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
题目说 one pass ; 那么,这样,用两个直指针; p先跑n步,然后q和p一起跑,那么p跑到最后,q就正好在倒数第n个上面了。
Calculate the length first, and then remove the nth from the beginning.
Use fast and slow pointers. The fast pointer is n steps ahead of the slow pointer. When the fast reaches the end, the slow pointer points at the previous element of the target element.
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
题目说 one pass ; 那么,这样,用两个直指针; p先跑n步,然后q和p一起跑,那么p跑到最后,q就正好在倒数第n个上面了。
Calculate the length first, and then remove the nth from the beginning.
public ListNode removeNthFromEnd(ListNode head, int n) { if(head == null) return null; //get length of list ListNode p = head; int len = 0; while(p != null){ len++; p = p.next; } //if remove first node int fromStart = len-n+1; if(fromStart==1) return head.next; //remove non-first node p = head; int i=0; while(p!=null){ i++; if(i==fromStart-1){ p.next = p.next.next; } p=p.next; } return head; }
Use fast and slow pointers. The fast pointer is n steps ahead of the slow pointer. When the fast reaches the end, the slow pointer points at the previous element of the target element.
public ListNode removeNthFromEnd(ListNode head, int n) { if(head == null) return null; ListNode fast = head; ListNode slow = head; for(int i=0; i<n; i++){ fast = fast.next; } //if remove the first node if(fast == null){ head = head.next; return head; } while(fast.next != null){ fast = fast.next; slow = slow.next; } slow.next = slow.next.next; return head; }
相关文章推荐
- nodejs中package.json文件模块依赖的版本格式
- Node.js的线程和进程*2014年4月的文章
- Node.js简介和安装
- lintcode: Insert Node in a Binary Search Tree
- LightOJ1094 - Farthest Nodes in a Tree(树的直径)
- GDataXMLNode应用
- nodejs中npm工具自身升级
- Nodejs v4.4.0API文档学习(2)Assert断言测试模块
- 使用rosserial把Arduino作为ROS一个Node遇到的一个问题
- LeetCode Populating Next Right Pointers in Each Node
- javascript创建node节点
- [LeetCode]117. Populating Next Right Pointers in Each Node II
- node.js入门(二) 模块 事件驱动
- node.js入门(一)
- [Node.js] Use "prestart" in scripts
- [Node.js] Using ES6 and beyond with Node.js
- node.js编写服务器
- LeetCode 25. Reverse Nodes in k-Group
- windows下安装nodejs简要步骤
- nodeJs--模块module.exports与实例化方法