[leetcode] 19. Remove Nth Node From End of List
来源:互联网 发布:python sql注入脚本 编辑:程序博客网 时间:2024/06/03 07:14
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个节点,题目难度为Easy。
题目的关键是如何找倒数第N个节点,有经验的同学可能很容易想到用双指针法,让fast指针先走N个节点,然后同时移动快慢指针,当fast指针到达链表尾部时slow指针指向的节点即是倒数第N个节点。另外需要注意的是,如果倒数第N个节点是头节点需要特殊处理,具体代码:
class Solution {public: ListNode* removeNthFromEnd(ListNode* head, int n) { ListNode* fast = head; ListNode* slow = head; ListNode* prev = NULL; int cnt = 0; while(fast && cnt<n) { fast = fast->next; cnt++; } while(fast) { fast = fast->next; prev = slow; slow = slow->next; } if(prev) { prev->next = slow->next; return head; } else { return slow->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
- Android API Guides---Media and Camera
- 智能指针C++
- 排序算法---希尔排序
- iOS学习笔记-----KVC,KVO与通知初探
- [堆 思路题] BZOJ 4524 [Cqoi2016]伪光滑数
- [leetcode] 19. Remove Nth Node From End of List
- Hadoop 1.x MapReduce最小驱动配置
- java4月18数组
- 吴恩达机器学习笔记_第四周
- HADOOP 分布模式
- Intent传值用法
- MATLAB 3
- 二叉树的创建和遍历方法(下)
- 实现圆形头像的几种方法