赞
踩
143. 重排链表
这题算是把三个easy题并一块了。
/** * 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; // 找出中点 int len = 0, halflen; ListNode* cur = head; while(cur){ len++; cur = cur->next; } halflen = len/2; int pos = halflen + (len%2); // 反转后半部的链表 cur = head; ListNode* pre = nullptr; for(int i=0;i<pos;i++){ pre = cur; cur = cur->next; } pre->next = nullptr; ListNode *another_head = reverseList(cur); // 合并两个链表 mergeTwoList(head,another_head); } // 链表的头插法反转链表 ListNode* reverseList(ListNode* head) { ListNode *newHead = nullptr,*nxt; while(head){ nxt = head->next; head->next = newHead; newHead = head; head = nxt; } return newHead; } // 双指针合并两个链表 void mergeTwoList(ListNode *h1,ListNode *h2){ ListNode *header = new ListNode , *cur = header; while(h1 && h2){ ListNode* h_1 = h1->next , *h_2 = h2->next; h1->next = h2; cur->next = h1; cur = h2; h1 = h_1; h2 = h_2; } if(h1) cur->next = h1; if(h2) cur->next = h2; delete header; } };
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。