LeetCode 143 重排链表-中等
生活随笔
收集整理的這篇文章主要介紹了
LeetCode 143 重排链表-中等
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
給定一個(gè)單鏈表 L:L0→L1→…→Ln-1→Ln ,
將其重新排列后變?yōu)?#xff1a; L0→Ln→L1→Ln-1→L2→Ln-2→…
你不能只是單純的改變節(jié)點(diǎn)內(nèi)部的值,而是需要實(shí)際的進(jìn)行節(jié)點(diǎn)交換。
示例 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;} }; 創(chuàng)作挑戰(zhàn)賽新人創(chuàng)作獎(jiǎng)勵(lì)來咯,堅(jiān)持創(chuàng)作打卡瓜分現(xiàn)金大獎(jiǎng)總結(jié)
以上是生活随笔為你收集整理的LeetCode 143 重排链表-中等的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: OPPO Reno11 / Pro 手机
- 下一篇: LeetCode 92反转链表||-中等