# leetcode刷题.143. 重排链表.每日打卡

class Solution {
public:
/* 链表反转 */
ListNode* reverse(ListNode* head) {

if (nullptr == head)
return head;

ListNode* p1 = nullptr, * p2 = head;
ListNode* p3 = p2->next;

while (nullptr != p3) {
p2->next = p1;
p1 = p2;
p2 = p3;
p3 = p3->next;
}
p2->next = p1;
return p2;
}

/* 两个链表交叉合并 */
void merge(ListNode* p1, ListNode* p2) {

if (nullptr == p2)
return;

ListNode* pp1 = p1, * pp2 = p2;
ListNode* pp3 = pp1->next;
ListNode* pp4 = pp2->next;
while (nullptr != pp1 && nullptr != pp2) {
pp1->next = pp2;
pp2->next = pp3;
pp1 = pp3;
pp2 = pp4;
if(nullptr != pp3) pp3 = pp3->next;
if(nullptr != pp4) pp4 = pp4->next;
}
}

void reorderList(ListNode* head) {

if (nullptr == head)
return;

ListNode* p1 = head, * p2 = head;
while (nullptr != p2) {
p2 = p2->next;
if (nullptr != p2) {
p2 = p2->next;
p1 = p1->next;
}
}

if (nullptr == p1) {
return;
}

p2 = p1->next;
p1->next = nullptr;

/* 对后半段链表进行反转，p2 */
ListNode* last = reverse(p2);

/* 交叉合并 */
merge(head, last);
}
};

07-11 227
07-12 276

05-12 3055
02-21 1万+
12-01 1万+
10-01 5万+
©️2020 CSDN 皮肤主题: 书香水墨 设计师:CSDN官方博客