反转链表—leetcode206
生活随笔
收集整理的這篇文章主要介紹了
反转链表—leetcode206
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
反轉一個單鏈表。
示例:
輸入: 1->2->3->4->5->NULL
輸出: 5->4->3->2->1->NULL
進階:
你可以迭代或遞歸地反轉鏈表。你能否用兩種方法解決這道題?
思路1:迭代法,代碼寫起來感覺啥都剛剛好,又是有邏輯的,核心就是把掃描到的節點不斷的前置,就是把cur->head = newhead
然后把?newhead更新為cur,newhead?=?cur
/*** Definition for singly-linked list.* struct ListNode {* int val;* ListNode *next;* ListNode(int x) : val(x), next(NULL) {}* };*/ class Solution { public:ListNode* reverseList(ListNode* head) {ListNode* newhead = NULL;ListNode* cur = head;while(cur!=NULL){ListNode* temp = cur->next;cur->next = newhead;newhead = cur;cur = temp;}return newhead;} };思路2 :遞歸法
/*** Definition for singly-linked list.* struct ListNode {* int val;* ListNode *next;* ListNode(int x) : val(x), next(NULL) {}* };*/ class Solution { public:ListNode* reverseList(ListNode* head) {return reverse(NULL,head);}ListNode* reverse(ListNode* pre,ListNode* cur){if(cur==NULL) return pre;ListNode* next = cur->next;cur->next = pre;return reverse(cur,next);} };?
總結
以上是生活随笔為你收集整理的反转链表—leetcode206的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 岛屿数量—leetcode200
- 下一篇: 课程表—leetcode207