LeetCode——019
来源:互联网 发布:男孩被父砍29刀 知乎 编辑:程序博客网 时间:2024/05/20 04:11
/*
19. Remove Nth Node From End of List My Submissions QuestionEditorial Solution
Total Accepted: 104327 Total Submissions: 355590 Difficulty: Easy
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
*/
/*
解题思路:
1.我们要删除单链表中的一个元素(在不变动其值得情况下),我们只能是先找到它的前一个节点,然后重新连接。在这里为了防止删除的是正数第一个节点,所以我们有必要加一个临时的头结点dummy。
2.采用快慢指针的思路,去定位倒数第n个节点。两个游标指针fast,slow。先让fast走n步,然后二者同时往下走。最终slow走到要删除节点的前一个元素,而fast走向NULL。
3.执行删除操作。返回dummy->next.
*/
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public: ListNode* removeNthFromEnd(ListNode* head, int n) { //使用快慢指针确定倒数第n个元素 ListNode* dummy=new ListNode(-1); dummy->next=head; ListNode* fast=head,*slow=dummy,*pre=dummy; for(int i=0;i<n;i++){ fast=fast->next; } while(fast){ fast=fast->next; slow=slow->next; } fast=slow->next; slow->next=fast->next; delete(fast); return dummy->next; }};
- LeetCode——019
- 开始刷刷Leetcode—leetcode第二题
- LeetCode —— Combinations
- LeetCode —— Triangle
- LeetCode —— Anagrams
- [leetcode] Subsets——@
- Permutations——LeetCode
- minimum_window_substring ——leetcode
- LeetCode——Candy
- LeetCode——Triangle
- LeetCode——Combinations
- LeetCode——Permutations
- *candy——leetcode
- gas_station——leetcode
- LeetCode——Candy
- LeetCode——Triangle
- LeetCode——Anagrams
- LeetCode——Subsets
- JVM的基本原理
- 代码托管和服务功能多元化,看码客帮如何做软件众包
- opengl新版本简单易懂的环境配置
- Android天气预报程序(四)
- 字节流与字符流的区别详解
- LeetCode——019
- 关于Google Chrome 浏览器的一些命令及用法
- LeetCode 232. Implement Queue using Stacks
- nyoj 183 赚钱了 bellmanford
- bootstrap修改默认字体,更换为微软雅黑或其他字体的方法
- dp【划分数】
- 网页前端的异常处理方法、异常处理系统及异常处理服务器
- TCP/IP三次握手与四次挥手
- 找寻路径从根root到节点p的路径函数