Leetcode19. 删除链表的倒数第 N 个结点
19. 删除链表的倒数第 N 个结点
自己纯手写第一题,递归有点冗杂,开辟了虚拟头节点,而且要特别注意边界条件(当倒数第n个正好是头节点时)。
** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode() : val(0), next(nullptr) {} * ListNode(int x) : val(x), next(nullptr) {} * ListNode(int x, ListNode *next) : val(x), next(next) {} * }; */ class Solution { public: int recursion(ListNode* node,ListNode* &head, int n){ if(node->next == nullptr){ int cnt = 0; return cnt; } int cnt = recursion(node->next, head, n); cnt ++; if(cnt == n){ if(node->next == head){ head = head->next; } else{ node->next = node->next->next; } } return cnt; } ListNode* removeNthFromEnd(ListNode* head, int n) { ListNode *node = new ListNode(-1); node->next = head; recursion(node, head, n); return head; } };
大佬的代码永远是那么简洁利落
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode() : val(0), next(nullptr) {} * ListNode(int x) : val(x), next(nullptr) {} * ListNode(int x, ListNode *next) : val(x), next(next) {} * }; */ class Solution { public: int cur = 0; ListNode* removeNthFromEnd(ListNode* head, int n) { if(head == nullptr) return nullptr; head->next = removeNthFromEnd(head->next, n); cur ++; if(cur == n) return head->next; return head; } };
大佬的时间0ms,我的递归4ms,但是我没看出来是由于哪个原因导致时间花费是数倍,感谢如果有好心大佬在评论区能指导一下。
最经典的解法莫过于双指针了。
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode() : val(0), next(nullptr) {} * ListNode(int x) : val(x), next(nullptr) {} * ListNode(int x, ListNode *next) : val(x), next(next) {} * }; */ class Solution { public: ListNode* removeNthFromEnd(ListNode* head, int n) { ListNode* first = head; ListNode* second = head; if(head == nullptr) return nullptr; int i = 0; while(i ++ < n){ first = first -> next;//快指针先走n步 } if(first == nullptr) return head = head->next;//如果快指针走到头了,说明倒数第n个节点是头节点 while(first->next != nullptr){ first = first -> next; second = second -> next; } second ->next = second->next->next; return head; } };
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· Vue3状态管理终极指南:Pinia保姆级教程