LeetCode-019 Remove Nth Node From End of List
来源:互联网 发布:瓷砖的重量怎么算法 编辑:程序博客网 时间:2024/06/12 19:17
Description
Given a linked list, remove the nth node from the end of list and return its head.
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.
Analyse
一道很有趣的题,题意很简单,就是删除链表倒数第n个的数,做法可以是,先跑一遍链表数出链表长度,然后再算出顺数第几个位置再删去即可,但这种方法需要遍历两次链表,但这道题有趣的是,题目叫我们可以尝试在一次遍历解决问题。其实也很简单,可以一头一尾两个指针同时遍历链表,其中两个指针的间距为n+1,这就能保证当你尾巴那个指针到达链表尾部的时候,头那个指针刚好指的是目标的前一个位置,然后再做一个删除操作即可。
Code
class Solution {public: ListNode* removeNthFromEnd(ListNode* head, int n) { ListNode* ans = new ListNode(-1); ans->next = head; ListNode* first = ans; ListNode* second = ans; for (int i = 0; i < n + 1; i++) { first = first->next; } while (first != NULL) { first = first->next; second = second->next; } ListNode* temp = second->next; delete(temp); second->next = second->next->next; return ans->next; }};
阅读全文
0 0
- LeetCode 019 Remove Nth Node From End of List
- LeetCode: Remove Nth Node From End of List [019]
- 【LeetCode OJ 019】Remove Nth Node From End of List
- leetcode 019 Remove Nth Node From End of List (Python)
- 019 Remove Nth Node From End of List [Leetcode]
- LeetCode 019 Remove Nth Node From End of List
- [LeetCode]019-Remove Nth Node From End of List
- LeetCode 019 Remove Nth Node From End of List
- LeetCode 019 Remove Nth Node From End of List
- LeetCode-019 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
- Shipyard -- Docker可视化管理工具安装与配置
- 学习Lambda表达式
- Programming Language Foundations.pdf 英文原版 免费下载
- VPS+SS搭建
- BZOJ2260 商店购物 BZOJ4349 最小树形图 坠小树形图 朱刘算法
- LeetCode-019 Remove Nth Node From End of List
- python字符串的拼接,文件的读入写出
- 虚幻4地形混合材质蓝图连接
- 【Scikit-Learn 中文文档】交叉验证
- Introducing Elixir.pdf 英文原版 免费下载
- 枚举类型中的values()方法初探
- A11_C#封装的委托
- 参数优化,iostat详解
- Leetcode 82. Remove Duplicates from Sorted List II