LeetCode记录之——Remove Nth Node From End of List
2014-10-27 00:00
295 查看
这次题目 Remove Nth Node From End of List
比较典型的链表题目吧,这种要求遍历次数为1的题目一般都是用多个指针实现。
思路:两个指针同时遍历,间隔为n,这样当前一个指针到达链表尾部,后一个指针正好到要删除的节点位置。
实现时发现,有一个特殊情况:({1},1),为了满足这个情况,则要将后一个指针正好事要删除的节点前一个位置,而不是正好是。
同时,这种思路下,应该在头指针前面加一个节点,然后开始遍历,而不是让指针慢一步。
代码:
比较典型的链表题目吧,这种要求遍历次数为1的题目一般都是用多个指针实现。
思路:两个指针同时遍历,间隔为n,这样当前一个指针到达链表尾部,后一个指针正好到要删除的节点位置。
实现时发现,有一个特殊情况:({1},1),为了满足这个情况,则要将后一个指针正好事要删除的节点前一个位置,而不是正好是。
同时,这种思路下,应该在头指针前面加一个节点,然后开始遍历,而不是让指针慢一步。
代码:
public class Solution { public ListNode removeNthFromEnd(ListNode head, int n) { ListNode slow = new ListNode(0); slow.next = head; head = slow; ListNode fast = slow.next; for(int i = n; i > 0; i--){ fast = fast.next; } while(fast != null){ fast = fast.next; slow = slow.next; } slow.next = slow.next.next; return head.next; } }
相关文章推荐
- 个人记录-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 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] 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: 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