class Solution {
public:
void reorderList(ListNode* head) {
int n=countList(head);//n 从0开始 如果head中只有一个元素的话返回值为0
if(n==0)
return;
if(n%2==0)//n为偶数
{
int i=0;
ListNode*temp=head;
ListNode*pre=temp;
temp=temp->next;
while(temp)
{
i++;
if(i==n/2)
break;
pre=temp;
temp=temp->next;
}
pre->next=NULL;
temp=reverseList(temp);
ListNode *l=head;
ListNode *r=temp;
head=l;
l=l->next;
while(l&&r)
{
head->next=r;
head=head->next;
r=r->next;
head->next=l;
head=head->next;
l=l->next;
}
if(r)
head->next=r;
if(l)
head->next=l;
}
else//n为奇数
{
int i=0;
ListNode*temp=head;
ListNode*pre=temp;
temp=temp->next;
while(temp)
{
i++;
if(i==(n+1)/2)
break;
pre=temp;
temp=temp->next;
}
pre->next=NULL;
temp=reverseList(temp);
ListNode *l=head;
ListNode *r=temp;
head=l;
l=l->next;
while(l&&r)
{
head->next=r;
head=head->next;
r=r->next;
head->next=l;
head=head->next;
l=l->next;
}
if(r)
head->next=r;
if(l)
head->next=l;
}
}
ListNode *reverseList(ListNode *head)
{
if(!head||!head->next)
return head;
ListNode *temp=head->next;
head->next=NULL;
while(temp)
{
ListNode *a=temp;
temp=temp->next;
a->next=head;
head=a;
}
return head;
}
int countList(ListNode *head)//如果有0个元素或者1个元素则返回0
{
int n=0;
if(!head)
return n;
head=head->next;
while(head)
{
n++;
head=head->next;
}
return n;
}
};
143. Reorder List
最新推荐文章于 2022-10-08 18:49:12 发布