给定一个单链表 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) {
deque<ListNode*> dq;
ListNode* temp = head;
while(temp){
dq.push_back(temp);
temp = temp->next;
}
while(!dq.empty()){
if(!temp){
temp = dq.front();
dq.pop_front();
}
else{
temp->next = dq.front();
dq.pop_front();
temp = temp->next;
}
// 不能对空队列进行pop操作
if(dq.empty())
break;
temp->next = dq.back();
dq.pop_back();
temp = temp->next;
}
if(temp)
temp->next = nullptr;
}
};
递归:
class Solution {
public:
void reorderList(ListNode* head) {
if(!head || !head->next || !head->next->next)
return;
// 找到倒数第二个节点
ListNode* last_2 = head;
while(last_2->next->next)
last_2 = last_2->next;
last_2->next->next = head->next;
head->next = last_2->next;
last_2->next = nullptr;
reorderList(head->next->next);
return;
}
};
还有一种思路是找到链表的中点(快慢指针),将后半段链表反转,再依次将两个链表插入相应位置:
class Solution {
public:
void reorderList(ListNode* head) {
if (head == nullptr) {
return;
}
ListNode* mid = middleNode(head);
ListNode* l1 = head;
ListNode* l2 = mid->next;
mid->next = nullptr;
l2 = reverseList(l2);
mergeList(l1, l2);
}
ListNode* middleNode(ListNode* head) {
ListNode* slow = head;
ListNode* fast = head;
while (fast->next != nullptr && fast->next->next != nullptr) {
slow = slow->next;
fast = fast->next->next;
}
return slow;
}
ListNode* reverseList(ListNode* head) {
ListNode* prev = nullptr;
ListNode* curr = head;
while (curr != nullptr) {
ListNode* nextTemp = curr->next;
curr->next = prev;
prev = curr;
curr = nextTemp;
}
return prev;
}
void mergeList(ListNode* l1, ListNode* l2) {
ListNode* l1_tmp;
ListNode* l2_tmp;
while (l1 != nullptr && l2 != nullptr) {
l1_tmp = l1->next;
l2_tmp = l2->next;
l1->next = l2;
l1 = l1_tmp;
l2->next = l1;
l2 = l2_tmp;
}
}
};
作者:LeetCode-Solution
链接:https://leetcode-cn.com/problems/reorder-list/solution/zhong-pai-lian-biao-by-leetcode-solution/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。