如有不对,不吝赐教
进入正题:
已知两个非降序链表序列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<stdio.h>
#include<malloc.h>
struct ListNode{
int data;
struct ListNode *next;
};
struct List{
struct ListNode *head;
struct ListNode *tail;
};
void AddNode(struct List *S,int data);
void Insert(struct List *S1,struct List *S2);
void Print(struct List *S);
int main(void)
{
struct List *S1,*S2; //S1,S2两个费降序链表头部信息
int input;
S1=(struct List *)malloc(sizeof(struct List));
S1->head=(struct ListNode *)malloc(sizeof(struct ListNode));
S2=(struct List *)malloc(sizeof(struct List));
S2->head=(struct ListNode *)malloc(sizeof(struct ListNode));
S1->tail=S1->head;
S2->tail=S2->head;
S1->tail->data=S2->tail->data=-1;
while(scanf("%d",&input),-1!=input)
AddNode(S1,input);
while(scanf("%d",&input),-1!=input)
AddNode(S2,input);
Insert(S1,S2);
Print(S1);
return 0;
}
void AddNode(struct List *S,int data)
{
struct ListNode *newOne;
newOne=(struct ListNode *)malloc(sizeof(struct ListNode));
newOne->next=NULL;
S->tail->data=data;
S->tail->next=newOne;
S->tail=newOne;
return ;
}
void Insert(struct List *S1,struct List *S2)
{
struct ListNode *cur=S1->head;
struct ListNode *temp;
if(cur->data==-1){
S1->head=S2->head;
S1->tail=S2->tail;
free(S2);
S2=NULL;
return ;
}
while(cur->next!=S1->tail){
if(cur->data<=S2->head->data&&cur->next->data>=S2->head->data){
temp=S2->head;
S2->head=S2->head->next; //变换S2
temp->next=cur->next;
cur->next=temp; //插入到S1链表中
}
cur=cur->next; //向后走
}
if(S2->head!=S2->tail){
cur->next=S2->head;
free(S1->tail);
S1->tail=S2->tail;
} //说明还有S2的链表没连上
free(S2);
S2=NULL;
return ;
}
void Print(struct List *S)
{
struct ListNode *cur=S->head;
if(cur==S->tail){
printf("NULL");
return ;
}
while(cur->next!=S->tail){
printf("%d ",cur->data);
S->head=S->head->next;
free(cur);
cur=NULL;
cur=S->head;
}
printf("%d",cur->data);
free(cur);
free(S);
cur=NULL;
S=NULL;
return ;
}
测试结果: