206. 反转链表
给你单链表的头节点 head
,请你反转链表,并返回反转后的链表。
1 struct ListNode{ 2 int val; 3 ListNode* next; 4 ListNode() : val(0), next(nullptr) {} 5 ListNode(int x) : val(x), next(nullptr) {} 6 ListNode(int x, ListNode* next) : val(x), next(next) {} 7 }; 8 class Solution { 9 public: 10 ListNode* reverseList(ListNode* head) { 11 if(head == nullptr || head->next == nullptr) return head; 12 stack<ListNode*>* sta = new stack<ListNode*>(); 13 ListNode* cur = head; 14 while(cur) 15 { 16 (*sta).push(cur); 17 cur = cur->next; 18 } 19 ListNode* res = (*sta).top(); 20 (*sta).pop(); 21 ListNode* r = res; 22 while(!(*sta).empty()) 23 { 24 r->next = (*sta).top(); 25 (*sta).pop(); 26 r = r->next; 27 r->next = nullptr; 28 } 29 return res; 30 } 31 ListNode* reverseList_diedai(ListNode* head){ 32 if(head == nullptr || head->next == nullptr) return head; 33 ListNode* pre = nullptr; 34 ListNode* cur = head; 35 ListNode* tmp; 36 while(cur) 37 { 38 tmp = cur->next; 39 cur->next = pre; 40 pre = cur; 41 cur = tmp; 42 } 43 return pre; 44 } 45 ListNode* reverseList_digui(ListNode* head){ 46 /* 这样先入递归,在修改指针,返回的会是最先进入循环的head 47 所以如果想要返回最后修改的节点,需要先修改*/ 48 // if(head == nullptr || head->next == nullptr) return head; 49 // ListNode* last = reverseList_digui(head->next); 50 // if(last==head) 51 // { 52 // last->next = nullptr; 53 // } 54 // else{ 55 // last->next = head; 56 // } 57 return reverse(NULL, head); 58 } 59 ListNode* reverse(ListNode* pre,ListNode* cur){ 60 if(cur == NULL) return pre; 61 ListNode* temp = cur->next; 62 cur->next = pre; 63 64 return reverse(cur,temp); 65 } 66 };
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库
· SQL Server 2025 AI相关能力初探
· 为什么 退出登录 或 修改密码 无法使 token 失效