
Reorder List
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}.
解题思路:将链表分为前后两部分两个链表,针对第二个子链表求倒序,最后将两个子链表合并。
//解题思路:将链表分为前后两部分两个链表,针对第二个子链表求倒序,最后将两个子链表合并。
class Solution {
public:
void reorderList(ListNode *head) {
if(head==NULL)
return;
int len=getlistlen(head);
ListNode *head1=NULL , *head2=NULL ;
dividelist( head, len , head1 , head2 );
head2 = reverseList(head2);
mergeList(head1, head2);
}
private:
int getlistlen(ListNode *head)
{
int len=0;
while(head)
{
len++;
head = head->next;
}
return len;
}
void dividelist(ListNode *head , int len , ListNode *&head1 , ListNode *&head2)
{
int half = (len+1)/2;
ListNode *first=head;
head1 = head;
for(int i=0; i<half-1; i++)
{
first = first->next;
}
head2 = first->next;
first->next = NULL;
}
ListNode* reverseList(ListNode* head)
{
if( head == NULL)
return NULL;
ListNode *p = head->next;
head->next = NULL;
while(p)
{
ListNode *temp = p;
p = p->next;
temp->next = head;
head = temp;
}
return head;
}
void mergeList(ListNode* head1, ListNode* head2)
{
while(head2)
{
ListNode *temp = head2;
head2 = head2->next;
temp->next = head1->next;
head1->next = temp;
head1 = head1->next->next;
}
}
};#include<iostream>
using namespace std;
#define N 4
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
void reorderList(ListNode *head) {
if(head==NULL)
return;
int len=getlistlen(head);
ListNode *head1=NULL , *head2=NULL ;
dividelist( head, len , head1 , head2 );
head2 = reverseList(head2);
mergeList(head1, head2);
}
private:
int getlistlen(ListNode *head)
{
int len=0;
while(head)
{
len++;
head = head->next;
}
return len;
}
void dividelist(ListNode *head , int len , ListNode *&head1 , ListNode *&head2)
{
int half = (len+1)/2;
ListNode *first=head;
head1 = head;
for(int i=0; i<half-1; i++)
{
first = first->next;
}
head2 = first->next;
first->next = NULL;
}
ListNode* reverseList(ListNode* head)
{
if( head == NULL)
return NULL;
ListNode *p = head->next;
head->next = NULL;
while(p)
{
ListNode *temp = p;
p = p->next;
temp->next = head;
head = temp;
}
return head;
}
void mergeList(ListNode* head1, ListNode* head2)
{
while(head2)
{
ListNode *temp = head2;
head2 = head2->next;
temp->next = head1->next;
head1->next = temp;
head1 = head1->next->next;
}
}
};
ListNode *creatlist()
{
ListNode *head = NULL;
ListNode *p;
for(int i=0; i<N; i++)
{
int a;
cin>>a;
p = (ListNode*) malloc(sizeof(ListNode));
p->val = a;
p->next = head;
head = p;
}
return head;
}
int main()
{
ListNode *list = creatlist();
Solution lin;
lin.reorderList(list);
for(int i=0; i<N; i++)
{
cout<<list->val;
list = list->next;
}
return 0;
}原文地址:http://blog.csdn.net/keyyuanxin/article/details/43833365