[LeetCode]19. Remove Nth Node From End of List
来源:互联网 发布:linux xz 编辑:程序博客网 时间:2024/06/16 04:44
题目描述: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为有效的输入,就不用判断n是否小于链表的长度。删除倒数第n个节点。需要在头结点前设置一个节点,让follow指针每次前进的时候都比p指针慢一个节点,方便删除倒数第n个节点。
public ListNode removeNthFromEnd(ListNode head, int n) { if(head==null)return null; //创建preHead,避免第一个节点为就为删除的节点。 ListNode preHead = new ListNode(0); preHead.next = head; ListNode p = head; //保证follow在p的后一个节点同步移动 ListNode follow = preHead; for(int i=0;i<n;i++){ p=p.next; } while(p!=null){ p=p.next; follow = follow.next; } follow.next = follow.next.next; return preHead.next; }
阅读全文
0 0
- 19. Remove Nth Node From End of List leetcode list
- [LeetCode]19.Remove Nth Node From End of List
- LeetCode 19. Remove Nth Node From End of List
- 19. Remove Nth Node From End of List Leetcode Python
- LeetCode --- 19. Remove Nth Node From End of List
- LeetCode 19.Remove Nth Node From End of List
- [Leetcode] 19. Remove Nth Node From End of List
- [leetcode] 19.Remove Nth Node From End of List
- <LeetCode OJ> 19. Remove Nth Node From End of List
- 19. Remove Nth Node From End of List LeetCode
- leetcode 19. Remove Nth Node From End of List
- [LeetCode OJ] 19. Remove Nth Node From End of List
- LeetCode 19. Remove Nth Node From End of List
- Leetcode:19. Remove Nth Node From End of List(JAVA)
- leetcode 19. Remove Nth Node From End of List
- Leetcode 19. Remove Nth Node From End of List
- 【LeetCode】19. Remove Nth Node From End of List
- leetcode 19.Remove Nth Node From End of List
- OpenCV直方图计算,以及颜色迁移
- QGis二次开发基础 -- 添加矢量要素功能
- 【二分法】LeetCode-Search Insert Position
- 拉格朗日对偶
- activity与fragment的区别
- [LeetCode]19. Remove Nth Node From End of List
- Linux 网络栈剖析
- Spring框架之IoC容器—ListableBeanFactory接口
- Scala继承的特点
- Ambari启用https访问(ssl)
- 转载 有哪些 Android 大牛的 blog 值得推荐?
- QGis二次开发基础 -- 矢量图层属性图表显示
- FPGA仿真--前仿真和后仿真
- 世界上第一款耳机