Leetcode: Remove Nth Node From End of List 总结
来源:互联网 发布:阿里云 注册域名送邮箱 编辑:程序博客网 时间:2024/06/03 16:28
题目大意:从一个单链表中删除倒数第k个节点。
理解:为了方便处理删除第1个,也就是倒数第n(链表长度)个节点,在给定的链表中增加首节点h,从h开始处理,最后返回h.next就可以了。记住:删除倒数第k个,也就是找到倒数第(k+1)个节点;考虑到链表中只有一个节点的情形。
本题要求最好只扫描一遍链表,本人采取的方法是:两个指针,先让一个指针走k+1步,然后两个指针同时向后移动,直到先走的指针为空(即链表尾)。
实现:
/** * 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; if(head.next == null) return null;// only one node ListNode h = new ListNode(1); // add a node as the head node h.next = head; ListNode p = h, q = h; int t = n + 1; while(t > 0) { q = q.next; t --; } while(q != null) { q = q.next; p = p.next; } q = p.next; p.next = q.next; return h.next; }}
0 0
- Leetcode: 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
- POJ 3678 深刻理解2SAT
- BNUOJ--29379 斩
- Get和Post请求的区别
- Struts2 -- 原理简述
- 黑马程序员-android之设计模式
- Leetcode: Remove Nth Node From End of List 总结
- windows下 用串行连接控制树莓派
- T-SQL查询处理执行顺序(二)
- PB之DWItemStatus
- EDID
- Flash Socket 和 Erlang Socket 通信的注意事项
- POJ 2251
- C语言中的左移右移
- 深入浅出TCP之半关闭与CLOSE_WAIT