#174 Remove Nth Node From End of List
来源:互联网 发布:fdd lte网络 编辑:程序博客网 时间:2024/06/12 01:44
题目描述:
Given a linked list, remove the nth node from the end of list and return its head.
Notice
The minimum number of nodes in list is n.
Example
Given linked list: 1->2->3->4->5->null
, and n = 2
.
After removing the second node from the end, the linked list becomes 1->2->3->5->null
.
Challenge
题目思路:Can you do it without getting the length of the linked list?
这题只要找到需要删除的node的前一个node的位置,就很容易办了。怎么找这个位置呢?我先用一个fast pointer,让它从dummy head开始先走n步;然后用一个slow pointer从dummy head开始跟它一起走,等fast走到最后一个node的时候,slow指向的位置就是我们想找的位置了。
Mycode (AC = 56ms):
/** * Definition of ListNode * class ListNode { * public: * int val; * ListNode *next; * ListNode(int val) { * this->val = val; * this->next = NULL; * } * } */class Solution {public: /** * @param head: The first node of linked list. * @param n: An integer. * @return: The head of linked list. */ ListNode *removeNthFromEnd(ListNode *head, int n) { // write your code here ListNode *dummy = new ListNode(0); dummy->next = head; // let fast ptr go n steps first ListNode *slow = dummy, *fast = dummy; int k = 0; while (k < n) { fast = fast->next; k++; } // find the ptr where ptr->next is the // element we want to delete while (fast->next) { slow = slow->next; fast = fast->next; } // delete the element slow->next = slow->next->next; return dummy->next; }};
0 0
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node from End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Hive与ETL基础—学习笔记[3]
- 正则表达式-切割
- MySQL中的共享锁与排他锁
- 实战c++中的vector系列--正确释放vector的内存(clear(), swap(), shrink_to_fit())
- hdu1573 X问题 一元模线性方程组
- #174 Remove Nth Node From End of List
- mac常用Terminal命令與快捷鍵參考
- react native 动态添加/渲染组件
- 堆和栈(C#)
- ext viewpoint简单例子
- iOS开发中 APP转让
- Mishka and trip 道路权值和
- Pro Android学习笔记(一五三):传感器(3):近距离传感器、温度传感器、气压传感器
- CAS 单点登陆