LeetCode (19)Remove Nth Node From End of List
来源:互联网 发布:javascript下拉菜单 编辑:程序博客网 时间:2024/05/13 14:46
(19)Remove Nth Node From End of List
题目:将一个链表的倒数第N个链节去掉。
例子:
所给的链表是: 1->2->3->4->5,同时 n = 2。移除链节之后,链表为: 1->2->3->5。
根据题目,想到的就是通过从前向后计算链表长度然后去掉第len - n个链节就可以了。
我觉得可能会有更好的算法,就看了一下几个博客,使用的方法是将两个指针中间间隔n个,一起向后查找,直到后面的指针为NULL,但是我考虑之后觉得的确是一种好想法,但是却觉得复杂度差不多,所以就没改自己的代码,下面是我写的代码:
class Solution {public: ListNode* removeNthFromEnd(ListNode* head, int n) { int len = 0; if(n == 0){ return head; } ListNode *p = head, *q = head, *result = head; while(p->next != NULL){ len ++; p = p->next; } len ++; if(n > len){ return head; } if(n == len){ return head->next; } for(int i = 1;i < len - n; i ++){ q = q->next; } q->next = q->next->next; return result; }};
0 0
- LeetCode(19) Remove Nth Node From End of List
- LeetCode (19)Remove Nth Node From End of List
- [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
- 05_事件处理
- 17.4.24 漫画与人脸识别(四) Face Painting: querying art with photos 小感
- sharedPreferences-记住密码(5)
- for循坏遍历list过程中remove某个元素出错,从源码角度解释
- YDT-Routesim学习(二)
- LeetCode (19)Remove Nth Node From End of List
- git和github和android studio的开始使用
- HZAU 1199 Little Red Riding Hood(水DP)
- php curl 抓取数据
- 单播、多播(组播)和广播的区别
- 第三届蓝桥杯第九题 足球比赛
- PDO链接数据库,PDO事物处理
- 卡玫妮董事长是谁?诚信塑造微商品牌示范作用
- C#之------迭代器