#include <stdio.h>
typedef int Elem;
typedef struct LinkNode
{
Elem data;
struct LinkNode *next;
}LinkNode,*LinkList;
void createLinkList(LinkList L,int arr[],int length){
//L=(LinkNode *)malloc(sizeof(LinkNode));
LinkNode *pTail=L;
int index=0;
while(index<length){
LinkNode *pNode=(LinkNode *)malloc (sizeof(LinkNode));
pNode->data=arr[index];
pNode->next=NULL;
pTail->next=pNode;
pTail=pTail->next;
index++;
}
}
void reverseLink(LinkList L)
{
LinkNode *pNode=L->next;
L->next=NULL;
while(pNode!=NULL)
{
//printf("%d\n",pNode->data);
LinkNode *temp=pNode;
pNode=pNode->next;
temp->next=L->next;
L->next=temp;
//pNode=pNode->next;
}
}
void combineAB(LinkList La,LinkList Lb)
{
//int cnt=0;
if(NULL==La||Lb==NULL)
{
return ;
}
LinkNode *pLa=La->next;
LinkNode *pLb=Lb->next;
free(Lb);
La->next=NULL;
LinkNode *pTail=La;
while(pLa!=NULL&&pLb!=NULL)
{
if(pLa->data < pLb->data)
{
LinkNode *temp=pLa;
pLa=pLa->next;
temp->next=NULL;
pTail->next=temp;
//printf("%d\n",pLa->data);
}
else
{
LinkNode *temp=pLb;
pLb=pLb->next;
temp->next=NULL;
pTail->next=temp;
// printf("%d\n",pLb->data);
}
pTail=pTail->next;
}
if(pLa!=NULL)
{
pTail->next=pLa;
}
if(pLb!=NULL)
{
pTail->next=pLb;
}
LinkNode *p=La->next;
while(p!=NULL){
printf("%d ",p->data);
p=p->next;
}
}
void print(LinkList L){
LinkNode *pNode=L->next;
while(pNode!=NULL){
printf("%d ",pNode->data);
pNode=pNode->next;
}
}
int main(){
LinkList La,Lb;
La=(LinkNode *)malloc(sizeof(LinkNode));
La->next=NULL;
Lb=(LinkNode *)malloc(sizeof(LinkNode));
Lb->next=NULL;
int arrA[100]={0};
int arrB[100]={0};
int a_length=0,b_length=0;
int enterData=9999;
while(scanf("%d",&enterData)!=EOF){
if(enterData==9999){
break;
}
else{
arrA[a_length]=enterData;
a_length++;
}
}
while(scanf("%d",&enterData)!=EOF){
if(enterData==9999){
break;
}
else{
arrB[b_length]=enterData;
b_length++;
}
}
createLinkList(La,arrA,a_length);
createLinkList(Lb,arrB,b_length);
//print(La);
// printf("\n");
//print(Lb);
// printf("\n");
reverseLink(Lb);
// print(Lb);
combineAB(La,Lb);
//print(Lab);
}
将一个升序链表和一个降序链表合并成为一个有序链表
最新推荐文章于 2022-03-15 16:37:45 发布