class Solution public int f=0; ListNode ans; void dfsListNode pListNode q if!q f=1; return; dfsqq-next; iff==1 ans = q;
代码的实现是对的,但是不够简洁,可以用递归代替dfs函数,避免使用全局变量f和ans,同时代码也更加清晰易懂。
改进后的代码如下:
class Solution { public: ListNode* reverseList(ListNode* head) { if(head==nullptr||head->next==nullptr) return head; ListNode* p = reverseList(head->next); head->next->next = head; head->next = nullptr; return p; } };
原文地址: https://www.cveoy.top/t/topic/fHkj 著作权归作者所有。请勿转载和采集!