题解 | #按照左右半区的方式重新组合单链表#
按照左右半区的方式重新组合单链表
http://www.nowcoder.com/practice/a7a348bdb4634e228cf7704c8a2a8bda
# include <bits/stdc++.h>
using namespace std;
struct list_node{
int val;
struct list_node * next;
};
list_node * input_list(void)
{
int n, val;
list_node * phead = new list_node();
list_node * cur_pnode = phead;
scanf("%d", &n);
for (int i = 1; i <= n; ++i) {
scanf("%d", &val);
if (i == 1) {
cur_pnode->val = val;
cur_pnode->next = NULL;
}
else {
list_node * new_pnode = new list_node();
new_pnode->val = val;
new_pnode->next = NULL;
cur_pnode->next = new_pnode;
cur_pnode = new_pnode;
}
}
return phead;
}
list_node * relocate(list_node * head)
{
//////在下面完成代码
if(head==NULL||head->next==NULL||head->next->next==NULL)
return head;
//找到中间节点把链表分成左半区和右半区
list_node*fast=head->next,*slow=head;//快慢指针
while(fast->next&&fast->next->next){
fast=fast->next->next;
slow=slow->next;
}
//此时slow指的就是左半区的最后一个节点
list_node*newHead=slow->next;
slow->next=NULL;
list_node*resHead=new list_node,*p=resHead;
p->next=NULL;
list_node*next1=NULL,*next2=NULL;
while(head&&newHead){
next1=head->next;
next2=newHead->next;
p->next=head;
p=p->next;
p->next=newHead;
p=p->next;
head=next1;
newHead=next2;
}
if(newHead){
p->next=newHead;
p=p->next;
p->next=NULL;
return resHead->next;
}
p->next=NULL;
return resHead->next;
}
void print_list(list_node * head)
{
while (head != NULL) {
printf("%d ", head->val);
head = head->next;
}
puts("");
}
int main ()
{
list_node * head = input_list();
list_node * new_head = relocate(head);
print_list(new_head);
return 0;
}
using namespace std;
struct list_node{
int val;
struct list_node * next;
};
list_node * input_list(void)
{
int n, val;
list_node * phead = new list_node();
list_node * cur_pnode = phead;
scanf("%d", &n);
for (int i = 1; i <= n; ++i) {
scanf("%d", &val);
if (i == 1) {
cur_pnode->val = val;
cur_pnode->next = NULL;
}
else {
list_node * new_pnode = new list_node();
new_pnode->val = val;
new_pnode->next = NULL;
cur_pnode->next = new_pnode;
cur_pnode = new_pnode;
}
}
return phead;
}
list_node * relocate(list_node * head)
{
//////在下面完成代码
if(head==NULL||head->next==NULL||head->next->next==NULL)
return head;
//找到中间节点把链表分成左半区和右半区
list_node*fast=head->next,*slow=head;//快慢指针
while(fast->next&&fast->next->next){
fast=fast->next->next;
slow=slow->next;
}
//此时slow指的就是左半区的最后一个节点
list_node*newHead=slow->next;
slow->next=NULL;
list_node*resHead=new list_node,*p=resHead;
p->next=NULL;
list_node*next1=NULL,*next2=NULL;
while(head&&newHead){
next1=head->next;
next2=newHead->next;
p->next=head;
p=p->next;
p->next=newHead;
p=p->next;
head=next1;
newHead=next2;
}
if(newHead){
p->next=newHead;
p=p->next;
p->next=NULL;
return resHead->next;
}
p->next=NULL;
return resHead->next;
}
void print_list(list_node * head)
{
while (head != NULL) {
printf("%d ", head->val);
head = head->next;
}
puts("");
}
int main ()
{
list_node * head = input_list();
list_node * new_head = relocate(head);
print_list(new_head);
return 0;
}