7-1 两个有序链表序列的合并
已知两个非降序链表序列S1与S2,设计函数构造出S1与S2合并后的新的非降序链表S3。
输入格式:
输入分两行,分别在每行给出由若干个正整数构成的非降序序列,用−1表示序列的结尾(−1不属于这个序列)。数字用空格间隔。
输出格式:
在一行中输出合并后新的非降序链表,数字间用空格分开,结尾不能有多余空格;若新链表为空,输出NULL。
输入样例:
1 3 5 -1
2 4 6 8 10 -1
输出样例:
1 2 3 4 5 6 8 10
#include<iostream>
using namespace std;
struct node
{
int num;
struct node *next;
};
struct node *creat(struct node *head){
struct node *p,*q;
int num;
q = head;
while(~scanf("%d", &num)){
if(num == -1){
break;
}
p = (struct node*)malloc(sizeof(struct node));
p->next = NULL;
p->num = num;
q->next = p;
q = q->next;
}
return head;
};
struct node *sort_struct(struct node *head1, struct node *head2)
{
struct node *p,*p1,*p2,*q1, *q2;
struct node *head;
head = (struct node *)malloc(sizeof(struct node));
p = head;
q1 = head1;
q2 = head2;
p1 = head1 -> next;
p2 = head2 -> next;
while(p1!=NULL && p2!=NULL)
{
if(p1->num < p2 ->num){
p -> next = p1;
q1 -> next = p1->next;
p1 = q1->next;
}else{
p -> next = p2;
q2 ->next = p2 -> next;
p2 = q2 -> next;
}
p = p -> next;
}
if(p1 == NULL){
p -> next = p2;
}else{
p -> next = p1;
}
return head;
};
void print(struct node *head)
{
struct node *p;
p = head -> next;
if(head->next == NULL){
printf("NULL");
}
while(p != NULL)
{
if(p->next == NULL){
printf("%d\n", p->num);
}else{
printf("%d ", p->num);
}
p = p->next;
}
}
int main()
{
struct node *head,*head1;
head = (struct node*)malloc(sizeof(struct node));
head1 = (struct node*)malloc(sizeof(struct node));
head = creat(head);
head1 = creat(head1);
head = sort_struct(head, head1);
print(head);
return 0;
}
做这道题还有一个小小的疑问,就是条件语句的简写形式。
题目中的输出是使用了if —— else 语句。
原来我还学习过一种形式。是形似
printf("%d%c",p->num p->next==NULL?" ":"");