leetcode 19. Remove Nth Node From End of List
来源:互联网 发布:excel怎么对比数据 编辑:程序博客网 时间:2024/06/15 02:59
这道题我就是用一个节点把链表遍历,一个节点保存之前的节点,当遇到想删的节点的时候删除之后,删除节点的下一个节点连接到之前保存的节点。
/** * 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) { int head_lens = 1; if(!head || !head->next) return NULL; ListNode *tmp = head; ListNode *pre_node = NULL; while(tmp !=NULL) { head_lens++; tmp = tmp->next; } head_lens -= n; tmp = head; ListNode *tmp_remove = NULL; while(tmp !=NULL) { head_lens--; if(head_lens == 0) { if(tmp == head) return head->next; pre_node->next = tmp->next; tmp_remove = tmp; if(tmp_remove) delete tmp_remove; return head; } pre_node = tmp; tmp = tmp->next; } return head; }};
还有一个是top solution,写得真好呀!非常优雅。非常佩服,希望有一天我也可以写出这么好的代码。它的思想就是比如1,3,2,4,6,5,这样的数组。比如要删除n=2,指针a先跳到第二个节点,然后开始和另外一个新的节点b一起行动,等a结束之后,b也到了它要去的地方。完美~
然后但是我发现时间上它并没有比我好,和我一样。
class Solution{public: ListNode* removeNthFromEnd(ListNode* head, int n) { ListNode** t1 = &head, *t2 = head; for(int i = 1; i < n; ++i) { t2 = t2->next; } while(t2->next != NULL) { t1 = &((*t1)->next); t2 = t2->next; } *t1 = (*t1)->next; return head; }};
1 0
- 19. Remove Nth Node From End of List leetcode list
- [LeetCode]19.Remove Nth Node From End of List
- LeetCode 19. Remove Nth Node From End of List
- 19. Remove Nth Node From End of List Leetcode Python
- 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 OJ> 19. Remove Nth Node From End of List
- 19. Remove Nth Node From End of List LeetCode
- leetcode 19. Remove Nth Node From End of List
- [LeetCode OJ] 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(JAVA)
- 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
- Android开发实例之登录界面的实现
- spring aop理解二:spring aop 注册和创建代理
- A. Xenia and Divisors codeforces-problem-342A
- Cassandra 3.x官方文档_数据库内部
- 运行新项目的时候 出现 The type javax.servlet.http.HttpServletRequest cannot be resolved.
- leetcode 19. Remove Nth Node From End of List
- 女程序员发展之路
- android studio设置自动导入
- 【寒江雪】模板技术实现镜面特效
- ObjectAnimator设置动画
- android仿ios圆形头像
- javaWeb 08 tomcat服务器
- Android Retrofit 2.0 使用-补充篇
- web.xml is missing and <failOnMissingWebXml> is set to true