[LeetCode OJ] Reorder List—Given a singly linked list L: L0→L1→…→Ln-1→Ln, reorder it to: L0→Ln→L1→Ln-1→L2→Ln-2→…

时间:2023-03-09 15:58:34
[LeetCode OJ] Reorder List—Given a singly linked list L: L0→L1→…→Ln-1→Ln, reorder it to: L0→Ln→L1→Ln-1→L2→Ln-2→…

For example,
Given {1,2,3,4}, reorder it to {1,4,2,3}.

 /**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
void reorderList(ListNode *head) {
//求链表的总长度len
if(head==NULL)
return;
int len=;
ListNode *p = head; //tail用于指向整个链表的尾节点
while(p!=NULL)
{
p = p->next;
len++;
}
//将链表拆成两半,并将后半部分的链表顺序倒置,如原来链表为L1->L2->L3->L4->L5->L6->L7,现在得到两个链表L1->L2->L3->L4和L7->L6->L5
int i=;
ListNode * h1 = head;
ListNode * h2 = head ,*pre;
while(i<(len+)/)
{
pre = h2;
h2 = h2->next;
i++;
}
pre->next = NULL; //h1指向拆分后得到的第一个链表的第一个节点,并将第一个链表的最后一个节点的指针域置为NULL; h2指向拆分后得到的第二个链表的第一个节点,到这一步尚未对第二个链表倒置 //对第二个链表进行倒置
ListNode * temp;
p = h2;
if(p!=NULL)
{ h2 = h2->next;
p->next = NULL;
while(h2!=NULL)
{
temp = h2;
h2 = h2->next;
temp->next = p;
p = temp;
}
}
h2 = p; //由两个链表L1->L2->L3->L4和L7->L6->L5按如下方式得到所求的第三个链表,将第一个链表的第一个节点连接到第三个链表的末端,再将第二个链表的第一个节点连接到第三个链表的末端,以此类推,直到两个链表都为空
//得到的第三个链表便是L1->L7->L2->L6->L3->L5->L4
ListNode * tail = h1;
h1 = h1->next;
i = ;
while(h1!=NULL || h2!=NULL)
{
tail->next = (++i%)? h2 : h1;
tail = tail->next;
(i%) ? (h2 = h2->next) : (h1 = h1->next);
}
return;
}
};