题目链接:
https://leetcode.com/problems/reorder-list/description/
描述
Given a singly linked list L: L0?L1?…?Ln-1?Ln,
reorder it to: L0?Ln?L1?Ln-1?L2?Ln-2?…
You must do this in-place without altering the nodes’ values.
输入
For example,
Given {1,2,3,4},
输出
reorder it to {1,4,2,3}.
样例输入
样例输出
算法思想:
先把表等分成a与b两个链表,然后把b逆序,最后把a和b链表交叉合并起来即可
源代码
class Solution {
public:
void reorderList(ListNode* head) {
if (!head)
return ;
ListNode *a, *b;
//分离链表分成一半一半
a = head;
b = head->next;
while (b)
{
b = b->next;
if (b)
{
a = a->next;
b = b->next;
}
}
b = a->next;
a->next = NULL;
a = head;
//让b链表逆序
if (b)
{
ListNode *current = b->next;
ListNode *tem = current;
b->next = NULL;
while (current)
{
current = current->next;
tem->next = b;
b = tem;
tem = current;
}
}
//合并2个链表
ListNode *a1, *a2, *b1;
a1 = a; a2 = a1->next;
b1 = b;
while (b)
{
b = b->next;
a1->next = b1;
b1->next = a2;
b1 = b;
a1 = a2;
if (a1)
a2 = a1->next;
}
}
};
最优源代码