leetcode 19. Remove Nth Node From End of List
2017-01-11 23:57
337 查看
这道题我就是用一个节点把链表遍历,一个节点保存之前的节点,当遇到想删的节点的时候删除之后,删除节点的下一个节点连接到之前保存的节点。
还有一个是top solution,写得真好呀!非常优雅。非常佩服,希望有一天我也可以写出这么好的代码。它的思想就是比如1,3,2,4,6,5,这样的数组。比如要删除n=2,指针a先跳到第二个节点,然后开始和另外一个新的节点b一起行动,等a结束之后,b也到了它要去的地方。完美~
然后但是我发现时间上它并没有比我好,和我一样。
/** * 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; } };
相关文章推荐
- [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
- leetcode19-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
- LeetCode19——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 (2 solutions)
- [Leetcode 19] 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. 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