LeetCode#19 Remove Nth Node From End of List
来源:互联网 发布:kord机枪 知乎 编辑:程序博客网 时间:2024/06/06 04:16
key: two pointers, one runs fast than the other n+1 steps
Runtime: 4 ms / beats 37.25%
Reference:discuss
/** * 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 *s, *e; s = e = head; int i; for(i = 0; i < n+1 && e != NULL; i++) { e = e->next; } ListNode *temp; if(i < n+1) { temp = head; head = head->next; free(temp); return head; } while(e != NULL) { s = s->next; e = e->next; } temp = s->next; s->next = s->next->next;//ne free(temp); return head; }};
Update: add a header to reduce complicate ‘if’ cases later
Reference:Editorial Solution
/** * 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 *s, *e, header(0); header.next = head; s = e = &header; for(int i = 0; i < n+1; i++) { e = e->next; } while(e != NULL) { e = e->next; s = s->next; } ListNode *temp; temp = s->next; s->next = s->next->next; free(temp); return header.next; }};
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
- PHP file_put_contents&file_get_contents的使用
- js使用立即调用的函数表达式创建局部作用域问题
- dedecms织梦TAG标签显示每个标签共有多少篇文章的方法
- Mac显示或不显示隐藏文件操作命令
- android仿腾讯小火箭案例
- LeetCode#19 Remove Nth Node From End of List
- android面试专题(6)
- POJ 3641 Pseudoprime numbers(费马小定理,快速幂,数论)
- 使用SurfaceBiew录制视频
- 【打CF,学算法——三星级】CodeForces 701C They Are Everywhere
- Poj 3613 Cow Relays【Floyd+快速幂】
- 2016夏季练习——Prim
- 第一章 银联8583报文解析
- scala 学习笔记4 cache 和persist的区别