LeetCode 133 Remove Nth Node From End of List
来源:互联网 发布:非法网络彩票赌博 编辑:程序博客网 时间:2024/06/14 15:14
Given a linked list, remove the nth node from the end of list and return its head.
Given n will always be valid.
Try to do this in one pass.
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,再一起走。
小技巧:链表问题,新建一个dummy头总是很有帮助的。
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */public class Solution { public ListNode removeNthFromEnd(ListNode head, int n) { if(head == null) return null; ListNode dummy = new ListNode(0); dummy.next = head; //快慢指针法 ListNode fast = dummy; ListNode slow = dummy; while(n>0){ fast = fast.next; n--; } while(fast.next != null){ fast = fast.next; slow = slow.next; } slow.next = slow.next.next; return dummy.next; }}
0 0
- LeetCode 133 Remove Nth Node From End of List
- LeetCode[Linked List]: Remove Nth Node From End of List
- 19. Remove Nth Node From End of List leetcode list
- [Leetcode]LeetCode 19:Remove Nth Node From End of List
- LeetCode: Remove Nth Node From End of List
- LeetCode: Remove Nth Node From End of List
- [Leetcode] Remove Nth Node From End of List
- LeetCode: Remove Nth Node From End of List
- leetcode 40: Remove Nth Node From End of List
- [LeetCode] Remove Nth Node From End of List
- Leetcode 19 Remove Nth Node From End of List
- [Leetcode] Remove Nth Node From End of List
- [LeetCode]Remove Nth Node From End of List
- LeetCode-Remove Nth Node From End of List
- [LeetCode] Remove Nth Node From End of List
- LeetCode 19: Remove Nth Node From End of List
- LeetCode - Remove Nth Node From End of List
- LeetCode | Remove Nth Node From End of List
- 面试题3 二维数组中的查找
- 输入一个正整数n,返回一个最小正整数m(m至少是2位数),使得m的各位乘积等于n,例如输入36,输出49,输入100,输出455,对于某个n不存在这样的m,请返回-1。
- iOS内存错误EXC_BAD_ACCESS的解决方法
- 【C99标准翻译1】sizeof
- 获取句柄
- LeetCode 133 Remove Nth Node From End of List
- linux下目录详解
- Google-HK-2012-interview-"pizza"(1)
- 无线传感器网络路由协议AODV(Ad hoc on-demand distance vector routing)
- 十八届三中全会关于全面深化改革若干重大问题的决定
- Digital Ocean使用SSH Key登录
- 如何隐藏控制台窗口
- 并发问题:大数据量的访问
- Eclipse如何关联源码以及v4包关联源码