题解 | #合并两个有序的单链表#
合并两个有序的单链表
http://www.nowcoder.com/practice/98a51a92836e4861be1803aaa9037440
# 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 * merge_list(list_node * head1, list_node * head2)
{
//////在下面完成代码
list_node*newHead=new list_node,*p=newHead;
p->next=NULL;
list_node*next1=NULL,*next2=NULL;
while(head1&&head2){
next1=head1->next;
next2=head2->next;
if(head1->val<head2->val){
p->next=head1;
p=p->next;
head1=next1;
}
else if(head1->val==head2->val){
p->next=head1;
p=p->next;
head1=next1;
p->next=head2;
p=p->next;
head2=next2;
}
else{
p->next=head2;
head2=next2;
p=p->next;
}
}
while(head1){
next1=head1->next;
p->next=head1;
p=p->next;
p->next=NULL;
head1=next1;
}
while(head2){
next2=head2->next;
p->next=head2;
p=p->next;
p->next=NULL;
head2=next2;
}
return newHead->next;
}
void print_list(list_node * head)
{
while (head != NULL) {
printf("%d ", head->val);
head = head->next;
}
puts("");
}
int main ()
{
list_node * head1 = input_list();
list_node * head2 = input_list();
list_node * new_head = merge_list(head1, head2);
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 * merge_list(list_node * head1, list_node * head2)
{
//////在下面完成代码
list_node*newHead=new list_node,*p=newHead;
p->next=NULL;
list_node*next1=NULL,*next2=NULL;
while(head1&&head2){
next1=head1->next;
next2=head2->next;
if(head1->val<head2->val){
p->next=head1;
p=p->next;
head1=next1;
}
else if(head1->val==head2->val){
p->next=head1;
p=p->next;
head1=next1;
p->next=head2;
p=p->next;
head2=next2;
}
else{
p->next=head2;
head2=next2;
p=p->next;
}
}
while(head1){
next1=head1->next;
p->next=head1;
p=p->next;
p->next=NULL;
head1=next1;
}
while(head2){
next2=head2->next;
p->next=head2;
p=p->next;
p->next=NULL;
head2=next2;
}
return newHead->next;
}
void print_list(list_node * head)
{
while (head != NULL) {
printf("%d ", head->val);
head = head->next;
}
puts("");
}
int main ()
{
list_node * head1 = input_list();
list_node * head2 = input_list();
list_node * new_head = merge_list(head1, head2);
print_list(new_head);
return 0;
}