leetcode 19 removeNthFromEnd
来源:互联网 发布:数据集成工具 编辑:程序博客网 时间:2024/06/06 09:14
Given a linked list, remove the nth node from the end of list and return its head.
For example,
Given linked list: 1->2->3->4->5, and n = 2.
After removing the second node from the end, the linked list becomes 1->2->3->5.
Note:
Given n will always be valid.
Try to do this in one pass.
/** * 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) { vector<ListNode*> v; // gurantee the size is bigger than one; if (head->next == NULL) return NULL; ListNode* p = head; size_t id = 0; while (p -> next != NULL) { v.push_back(p); p = p->next; } // the last one; v.push_back(p); p = NULL; vector<ListNode*>::size_type size = v.size(); if (size - n == 0) { // delete the head p = head; head = head->next; free(p); } else { // will visit the struct before the one that will be deleted // assert(size - n - 1 >= 0); p = v[size - n - 1]; ListNode* pdel = p-> next; p->next = pdel->next; free(pdel); // pdel = NULL; // p = NULL; } return head; }}; // runtime distribution 54.48%
参考后
/** * 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) { // The "dummy" node is used to simplify some corner cases such as a // list with only one node, or removing the head of the list. ListNode *dummy = new ListNode(0); dummy -> next = head; ListNode *first = dummy; ListNode *second = dummy; // first pointer go first for (int i = 0; i < (n + 1); ++i) first = first->next; while (first != NULL) { first = first->next; second = second->next; } ListNode* pdel = second->next; second->next = pdel->next; free(pdel); return dummy->next; }}; // runtime distribution: 14.50% // i don't konw why
阅读全文
0 0
- 【leetcode c++】19 removeNthFromEnd
- leetcode 19 removeNthFromEnd
- removeNthFromEnd
- Leetcode 19
- Leetcode(19)
- leetcode 19 和leetcode 83
- leetcode 19: Edit Distance
- [leetcode 19] N-Queens
- LeetCode 19 Clone Graph
- LeetCode (19) Multiply Strings
- leetcode之-题19
- leetcode #19 in cp
- leetCode练习(19)
- (java)leetcode-19
- Leetcode刷题(19)
- [Leetcode] 82, 61, 19
- 4.19 leetcode -19 candy
- LeetCode刷题(19)
- Kafka中时间轮分析与Java实现
- 求一个数组的子数组,使的该子数组的和是所有子数组中的最大值
- Maven之没有编译器(JDK)-yellowcong
- log日志配置简述
- Unity19--物体自动沿固定路线走,自动寻路
- leetcode 19 removeNthFromEnd
- 差不多女孩
- jQuery
- Android----AsyncTask和Handler对比
- 1>> socketserver 学习
- jsp基础语法
- 合法括号子段 51Nod
- 浅谈unsigned int与int相加的问题
- IOS UITableView总结