/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
/*
1.先找到链表的中点;
2.将链表从中间断开,然后翻转后半段链表;
3.用尾插法将后半段链表插入前半段的链表中(相隔一个节点再插入)。
*/
class Solution {
public:
void reorderList(ListNode *head) {
if(head == nullptr || head->next == nullptr) return;
//获得链表的后半段
ListNode *pre(head), *slow(head), *fast(head);
while(fast != nullptr && fast->next != nullptr){
pre = slow;
slow = slow->next;
fast = fast->next->next;
}
ListNode *q = slow;
q = reverse(q);//翻转后半部分的链表
pre->next = nullptr;
ListNode *p = head;
ListNode *tmp;
while(p != nullptr){//尾插法插入后半部分的链表结点
tmp = q;
q = q->next;
tmp->next = p->next;
p->next = tmp;
p = tmp->next;//下一个插入位置
}
if(q != nullptr) tmp->next = q;
}
ListNode* reverse(ListNode *head){
if(head == nullptr || head->next == nullptr) return head;
ListNode dummy(-1);
dummy.next = head;
ListNode *p(head->next);
head->next = nullptr;
ListNode *tmp;
while(p != nullptr){//头插法,翻转链表
tmp = p;
p = p->next;
tmp->next = dummy.next;
dummy.next = tmp;
}
return dummy.next;
}
};
12-19
12-19
12-19
364

被折叠的 条评论
为什么被折叠?



