合并单向有序列表

来源:互联网 发布:mac 快捷键设置没有用 编辑:程序博客网 时间:2024/06/08 11:05
#include <stdio.h>#include <stdlib.h>typedef int ElementType;typedef struct Node *PtrToNode;typedef struct Node {    ElementType Data;    PtrToNode   Next;};typedef PtrToNode List;//链表指针List Read();void Print( List L );List Merge( List L1, List L2 );int main(){    List L1, L2, L;    L1 = Read();    L2 = Read();    L = Merge(L1, L2);    Print(L);    Print(L1);    Print(L2);    return 0;}List Read(){int N=0,i=0;int x;scanf("%d",&N);PtrToNode head;//尾插法需要一个开始指向头部的指针PtrToNode tail;head=(PtrToNode)malloc(sizeof(struct Node));head->Next=NULL;tail=head;for(i=0;i<N;i++){scanf("%d",&x);PtrToNode templeNode;templeNode=(PtrToNode)malloc(sizeof(struct Node));templeNode->Data=x;tail->Next=templeNode;//将当前尾部的指针指向新节点tail=templeNode;//将新节点作为尾部}tail->Next=NULL;return head;}void Print(List tmp){    PtrToNode p=tmp;    if(!(p->Next))    {        printf("NULL");    }    while(p->Next)    {        printf("%d ",p->Next->Data);        p=p->Next;    }    printf("\n");}List Merge( List L1, List L2 ){    PtrToNode newListhead,newListtail;    newListhead=(PtrToNode)malloc(sizeof(struct Node));    newListhead->Next=NULL;    newListtail=newListhead;    while(L1->Next!=NULL&&L2->Next!=NULL)//首先循环两个元素都非空的部分    {        if(L1->Next->Data<=L2->Next->Data)        {            newListtail->Next=L1->Next;//将L1的元素查入到新表            newListtail=L1->Next;//改变新表尾            L1->Next=newListtail->Next;//将L1的表向后移动        }        else        {            newListtail->Next=L2->Next;            newListtail=L2->Next;            L2->Next=newListtail->Next;        }    }    if(L1->Next==NULL)    {        while(L2->Next!=NULL)        {            newListtail->Next=L2->Next;            newListtail=L2->Next;            L2->Next=newListtail->Next;        }    }    if(L2->Next==NULL)    {        while(L1->Next!=NULL)            {                newListtail->Next=L1->Next;                newListtail=L1->Next;                L1->Next=newListtail->Next;            }    }    newListtail->Next=NULL;    return newListhead;}

0 0
原创粉丝点击