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}
.
把后面的部分插入前面。
中心思想,将链表重中间断开,然后把后面的链表部分倒序,之后把后面链表的头节点依次插入到head链表里面。
其代码如下。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* reverseList(struct ListNode* head);
int LengthList(struct ListNode* head);
void reorderList(struct ListNode* head)
{
if(head==NULL||head->next==NULL)
return ;
int mid;
int length;
struct ListNode* pCurrent=head;
length=LengthList(pCurrent);
mid=(length+1)/2; //3 应该是第2个,以后也是在后面一个
//找到中间节点,分成两条链表,//mid 后面哪一个开始
struct ListNode* pCurrentmid=head;
struct ListNode* pCurrentmidFront;
while(mid--)
{
pCurrentmidFront=pCurrentmid;
pCurrentmid=pCurrentmid->next;
//mid=1,最后一个设置为null
}
struct ListNode* pCurrentMidafter=pCurrentmid; //3--->1
pCurrentmidFront->next=NULL; //让他变成两个链表
//翻转pCurrentMidafter
pCurrentMidafter=reverseList(pCurrentMidafter);
//DisplayList(pCurrentMidafter);
//DisplayList(head);
// //将翻转后的链表插入到head链表中..
pCurrent=head;
while(pCurrent!=NULL&&pCurrentMidafter!=NULL)
{
pCurrentmidFront=pCurrentMidafter;
pCurrentMidafter=pCurrentMidafter->next;
//插入
pCurrentmidFront->next=pCurrent->next;
pCurrent->next=pCurrentmidFront; //放回原位
pCurrent=pCurrentmidFront->next;
}
}
int LengthList(struct ListNode* head)
{
if(head==NULL)
return 0;
int length=0;
struct ListNode* pCurrent=head;
while(pCurrent!=NULL)
{
length++;
pCurrent=pCurrent->next;
}
//free(pCurrent);
return length;
}
struct ListNode* reverseList(struct ListNode* head) {
struct ListNode* newhead;
newhead=NULL;
//这样就不需要翻转了
if (head==NULL||head->next==NULL)
{
return head;
}
struct ListNode* pCurrent=head; //一样的点
while(pCurrent!=NULL)
{
struct ListNode* tmp=pCurrent;
pCurrent=pCurrent->next;
tmp->next=newhead; //把节点放在节点前面,插入到链表的最前端
newhead=tmp;
}
return newhead;
}