leetcode 19: Remove Nth Node From End of List
来源:互联网 发布:java把html写入pdf 编辑:程序博客网 时间:2024/06/03 01:56
问题描述:
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.
思路:
题目看来挺简单,主要就是设置一个前行节点一个后行节点,同步控制两节点距离一直到链表末端。但是实践完成代码的思路上还是有一点点技巧和注意的。
这里我用了一个链表附加头节点,这样在删除头结点问题上可以很方便解决;然后注意要得到的节点应该是所要求删除节点的前一个节点;还有就是最后返回链表时,要返回更新后的head节点,因为head可能有改变。
代码:
/** * 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) { ListNode* prehead = new ListNode(-1); prehead->next = head; ListNode* bias = prehead; ListNode* targetpre = prehead; //bias move forward n steps for(int i = 0; i < n; i++) { if(bias == NULL) return head; bias = bias->next; } //bias point to the end, at the same time, target point to the previous node of the nth from the end. while(bias->next != NULL) { bias = bias->next; targetpre = targetpre->next; } ListNode* temp = targetpre->next; targetpre->next = temp->next; head = prehead->next; //update the new head delete temp; delete prehead; return head; }};
0 0
- [Leetcode]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, Easy] 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 Solutions
- 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 | #19 Remove Nth Node From End of List
- leetcode.19----------Remove Nth Node From End of List
- [Leetcode 19, Easy] 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 19 Remove Nth Node From End of List
- leetcode 19 Remove Nth Node From End of List
- AsyncTask execute 那些事
- HDU2084 数塔 【DP问题】
- OD发包断点
- 重新定义团队 谷歌的自由精神对所有公司都适用
- Synchronized block 为String 时的情况
- leetcode 19: Remove Nth Node From End of List
- 【算法】最小生成树——所有点成树有最小总权和
- Android Studio 学习笔记01
- 基于opencv的形态学滤波
- android自定义控件波纹ripple效果
- send断点数据地址
- 二叉查找树
- 简单的UIPickView功能
- selenium 操控浏览器