BM9. 删除链表的倒数第n个节点
描述
示例1
输入:
{1,2},2
输出:
{2}
C++ 解法, 执行用时: 2ms, 内存消耗: 300KB, 提交时间: 2020-12-02
/** * struct ListNode { * int val; * struct ListNode *next; * }; */ class Solution { public: /** * * @param head ListNode类 * @param n int整型 * @return ListNode类 */ ListNode* removeNthFromEnd(ListNode* head, int n) { // write code here if(head == NULL){ return head; } ListNode* dummy = new ListNode(0); dummy->next = head; head = dummy; ListNode* slow = head; ListNode* fast = head; for(int i = 0; i <n; i++){ fast = fast ->next; } while(fast->next != NULL){ fast = fast->next; slow = slow->next; } ListNode* temp = slow->next; slow ->next = slow->next->next; delete temp; return dummy->next; } };
C++ 解法, 执行用时: 2ms, 内存消耗: 300KB, 提交时间: 2020-10-30
/** * struct ListNode { * int val; * struct ListNode *next; * }; */ class Solution { public: /** * * @param head ListNode类 * @param n int整型 * @return ListNode类 */ ListNode* removeNthFromEnd(ListNode* head, int n) { // write code here if(head==NULL) { return head; } ListNode* a=new ListNode(0); a->next=head; head=a; ListNode* slow=head; ListNode* fast=head; for(int i=0;i<n;i++) { fast=fast->next; } while(fast->next!=NULL) { fast=fast->next; slow=slow->next; } ListNode* temp=slow->next; slow->next=slow->next->next; delete temp; return a->next; } };
C++ 解法, 执行用时: 2ms, 内存消耗: 320KB, 提交时间: 2020-12-07
/** * struct ListNode { * int val; * struct ListNode *next; * }; */ class Solution { public: /** * * @param head ListNode类 * @param n int整型 * @return ListNode类 */ ListNode* removeNthFromEnd(ListNode* head, int n) { if(head == NULL) { return head; } ListNode* p = new ListNode(0); p->next = head; head = p; ListNode* slow = head; ListNode* fast = head; for(int i = 0; i <n; i++) { fast = fast ->next; } while(fast->next != NULL) { fast = fast->next; slow = slow->next; } ListNode* temp = slow->next; slow ->next = slow->next->next; delete temp; return p->next; } };
C++ 解法, 执行用时: 2ms, 内存消耗: 328KB, 提交时间: 2021-05-31
/** * struct ListNode { * int val; * struct ListNode *next; * }; */ class Solution { public: /** * * @param head ListNode类 * @param n int整型 * @return ListNode类 */ ListNode* removeNthFromEnd(ListNode* head, int n) { ListNode* dummy = new ListNode(0); dummy->next = head; ListNode* fast = dummy; ListNode* slow = dummy; while (n--) // 题目保证 nn 一定是有效的 { fast = fast->next; } while (NULL != fast && NULL != fast->next) { fast = fast->next; slow = slow->next; } slow->next = slow->next->next; head = dummy->next; delete(dummy); return head; } };
C++ 解法, 执行用时: 2ms, 内存消耗: 328KB, 提交时间: 2021-05-24
/** * struct ListNode { * int val; * struct ListNode *next; * }; */ class Solution { public: /** * * @param head ListNode类 * @param n int整型 * @return ListNode类 */ ListNode* removeNthFromEnd(ListNode* head, int n) { // write code here ListNode *p=head; int i=0; while(p!=NULL) { i++; p=p->next; } if(n==i) { head=head->next; return head; } else { p=head; for(int j=0;j<i-n-1;j++) { p=p->next; } p->next=p->next->next; return head; } } };