LeetCode 143 重排链表-中等
生活随笔
收集整理的這篇文章主要介紹了
LeetCode 143 重排链表-中等
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
給定一個單鏈表 L:L0→L1→…→Ln-1→Ln ,
將其重新排列后變為: L0→Ln→L1→Ln-1→L2→Ln-2→…
你不能只是單純的改變節點內部的值,而是需要實際的進行節點交換。
示例 1:
給定鏈表 1->2->3->4, 重新排列為 1->4->2->3.
示例 2:
給定鏈表 1->2->3->4->5, 重新排列為 1->5->2->4->3.
代碼如下:
/*** 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:void reorderList(ListNode* head) {if (head==nullptr) return ;vector<ListNode*>v;ListNode*pre= head;while(pre){v.push_back(pre);pre = pre->next;}int i = 0;int j = v.size()-1;while(i<j){v[i]->next = v[j];i++;if (i==j) break;v[j]->next = v[i];j--;}v[i]->next = nullptr;} }; 創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎總結
以上是生活随笔為你收集整理的LeetCode 143 重排链表-中等的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: OPPO Reno11 / Pro 手机
- 下一篇: LeetCode 92反转链表||-中等