题目
给定一个单链表 L
的头节点 head
,单链表 L
表示为:
L0 → L1 → … → Ln - 1 → Ln
请将其重新排列后变为:
L0 → Ln → L1 → Ln - 1 → L2 → Ln - 2 → …
不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。
示例
输入:head = [1,2,3,4] 输出:[1,4,2,3]
解决方法
1. 使用快慢指针的方式,寻找链表的中间节点。
2.从中间节点的下一个节点为开头,将链表断成两半。
3. 对后半部分链表进行反转,如下图所示:
4. 将前半部分链表与反转后的后半部分链表进行合并。
ListNode* mergeList(ListNode* l1,ListNode* l2){
//分别用cur1和cur2记录下l1和l2的后继节点
ListNode* head = l1;
ListNode* cur1;
ListNode* cur2;
while(l1 != nullptr && l2 != nullptr){
cur1 = l1->next;
cur2 = l2->next;
l1->next = l2;
l1 = cur1;
l2->next = l1;
l2 = cur2;
}
return head;
}
代码实现
/**
* 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:
ListNode* reverseList(ListNode* head){
ListNode* pre = nullptr;
ListNode* cur = head;
ListNode* next;
while(cur != nullptr){
next = cur->next;
cur->next = pre;
pre = cur;
cur = next;
}
return pre;
}
ListNode* mergeList(ListNode* l1,ListNode* l2){
//分别用cur1和cur2记录下l1和l2的后继节点
ListNode* head = l1;
ListNode* cur1;
ListNode* cur2;
while(l1 != nullptr && l2 != nullptr){
cur1 = l1->next;
cur2 = l2->next;
l1->next = l2;
l1 = cur1;
l2->next = l1;
l2 = cur2;
}
return head;
}
void reorderList(ListNode* head) {
if(head==nullptr && head->next==nullptr){
return;
}
ListNode* slow = head;
ListNode* fast = head;
while(fast->next && fast->next->next){
slow = slow->next;
fast = fast->next->next;
}
ListNode* backHead = slow->next;
//以中间节点为开头,将链表断成两半。
slow->next = nullptr;
backHead = reverseList(backHead);
ListNode* res = mergeList(head,backHead);
}
};