每天一题LeetCode[第十一天]
来源:互联网 发布:搞笑特效软件 编辑:程序博客网 时间:2024/05/23 19:48
每天一题LeetCode[第十一天]
Remove Nth Node From End of List
Description:
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.Subscribe to see which companies asked this question.
翻译:
给一个链表,从最后一个当作第一个,删除第n个节点,再把最后的结果返回。例子: 给一个链表:1->2->3->4->5 n=2 在删除晚第n个节点后,链表为1->2->3->5注意:n值永远是合法的。尝试只要一次循环给出正确结果。
解题思路:
一开始题意理解错误,所以想不明白为什么这种难度的要设置成medium。以至于后面看Top Solution的时候,看不明白什么意思。又回过来看了一下题目,终于明白了。从后面算n个,难度在于你不知道总长度,还要倒着找第n个,要求只能循环一遍。
又在看了一遍Top Solution一下子明白了,原来如此,对于长度未知,但需要从后面倒着的需求,可以有这种解法:先让一个pointer走n步,在让另外一个节点从开始节点起步,两个pointers以相同的速度前进,这样两个pointer间距n个节点,当最后一个pointer到达节点,第一个pointer也就在从后往前数的第n个节点啦。
Java代码:
public class ListNode { int val; ListNode(int x) { val = x; } ListNode next;}public class Solution { public ListNode removeNthFromEnd(ListNode head, int n) { ListNode start=new ListNode(0); ListNode fast=start,slow=start; slow.next=head; for(int i=1;i<=n+1;i++){ fast=fast.next; } while (fast!=null){ fast=fast.next; slow=slow.next; } slow.next=slow.next.next; return start.next; }}
提高代码质量就是:积累精致的思路,优质的细节。
0 0
- 每天一题LeetCode[第十一天]
- 每天一题LeetCode[第十天]
- 每天一题LeetCode[第十三天]
- 每天一题LeetCode[第十五天]
- 每天一题LeetCode[第十七天]
- 每天一题LeetCode [第一天]
- 每天学习10句英语-第十一天
- 每天一题LeetCode [第二天]
- 每天一题LeetCode[第四天]
- 每天一题LeetCode[第五天]
- 每天一题LeetCode[第三天]
- 每天一题LeetCode[第六天]
- 每天一题LeetCode[第七天]
- 每天一题LeetCode[第八天]
- 每天一题LeetCode[第九天]
- 每天一题LeetCode[第十二天]
- 每天一题LeetCode[第十四天]
- 每天一题LeetCode[第十六天]
- 使用面向对象重构之-使用接口完成行为抽象
- response和request编码
- status
- 不得不放弃、祝你元宵节快乐!
- IO流_字符流、IO流小结、IO流案例总结
- 每天一题LeetCode[第十一天]
- Go语言技巧:使用select{}阻塞main函数
- 起床闹钟
- rpm与yum
- 亚足联联赛积分规则
- 回射客户-服务器模型(1)
- Python学习笔记:Python字符编码问题的经验小结
- CCF201409-5 拼图(30分)
- 用原生JS写无缝轮播