合并有序单链表

来源:互联网 发布:绝地求生优化补丁 编辑:程序博客网 时间:2024/06/11 13:29

考研进行时——今天的任务是完成两个有序单链表的合并。不多说,贴代码:

#include<stdio.h>#include<stdlib.h>typedef struct LNode{int data;struct LNode  *next; //指针域}*LNode;/*LNode HeadCreatList (LNode L)  //头插法建立链表{LNode s;int i;L->next=NULL;for ( i=1;i<10;i+=2){s=(LNode)malloc(sizeof(LNode));s->data=i;s->next=L->next; //将L指向的地址赋值给S;L->next=s;}return L;}*/LNode TailCreatList(LNode L,int i)  //尾插法建立链表{LNode s,r;r=L;for ( i;i<=10;i+=2){s=(LNode)malloc(sizeof(LNode));s->data=i;r->next=s;r=s;}    r->next=NULL;    return L;}LNode MergeList(LNode L1,LNode L2,LNode L3){    LNode s1,s2,t;    t=L3;    s1=L1->next;//指向L1的第一个结点    s2=L2->next;//指向L2的第一个结点    while(s1&&s2)    {        if(s1->data<=s2->data)  //比较结点数据域的大小        {            t->next=s1;         //s1小,则将其接在t的后面            t=t->next;s1=s1->next;        }        else                    //反之,则将s2接在t的后面        {            t->next=s2;            t=t->next;s2=s2->next;        }    }    if(s1)printf("通知:s2先空了    \n");//附加的通知信息    else printf("通知:s1先空了    \n");        while(s1)                       //最后将剩余的元素直接接到t后面        {            t->next=s1;            t=t->next;s1=s1->next;        }        while(s2)        {            t->next=s2;            t=t->next;s2=s2->next;        }    return L3;}void DisPlay(LNode L)           //打印链表{LNode p=L->next;while(p){printf ("%d ",p->data);p=p->next;}printf("\n");}int main (){LNode L1,L2,L3;L1=( LNode)malloc(sizeof( LNode));L2=(LNode)malloc(sizeof( LNode));L3=(LNode)malloc(sizeof( LNode));TailCreatList(L1,1);            //这里为了方便,均用尾插法建表printf("尾插法建立的链表L1:");DisPlay(L1);TailCreatList(L2,2);printf("尾插法建立的链表L2:");DisPlay(L2);//printf("%d %d",L1->next->data,L2->next->data);MergeList(L1,L2,L3);            //合并链表printf("L1,L2合并后的链表L3:");DisPlay(L3);                    //打印链表L3return 0;}
实验结果:



0 0