LeetCode 206. 反转链表
生活随笔
收集整理的這篇文章主要介紹了
LeetCode 206. 反转链表
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
解法一:迭代法
class Solution { public:ListNode* reverseList(ListNode* head) {if(!head)return NULL;auto p1 = head, p2 = p1->next;//定義兩個相鄰指針while(p2) {auto p3 = p2->next; //p3存儲p2的后繼節點p2->next = p1; //后面節點指針指向前面的節點p1 = p2;//雙指針統一向后偏移p2 = p3;} head->next=NULL;return p1;} };解法二:遞歸法
class Solution { public:ListNode* reverseList(ListNode* head) {if (!head || !head->next) return head;ListNode *tail = reverseList(head->next);head->next->next = head;head->next = nullptr;return tail;} };?
總結
以上是生活随笔為你收集整理的LeetCode 206. 反转链表的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: (Tree)二叉树基本操作
- 下一篇: Leetcode 260. 只出现一次的