合并两个有序链表,将两个升序链表合并为一个新的升序链表并返回。 新链表是通过拼接给定的两个链表的所有节点组成的。 例如:输入 1->2->4,1->3->4->5,输出:1->1->2->3->4->4->5

/*合并两个有序链表,将两个升序链表合并为一个新的升序链表并返回。
新链表是通过拼接给定的两个链表的所有节点组成的。
例如:输入 1->2->4,1->3->4->5,输出:1->1->2->3->4->4->5      */
#include <stdio.h>
#include <stdlib.h>
#define LEN sizeof(struct node)
typedef struct node{
    int data;
    struct node *next;
}List;

List *selectsort(List *head)
{
    List *p,*q,*min;
    int tmp;
    for(p=head;p->next!=NULL;p=p->next)
    {
        min=p;
        for(q=p->next;q!=NULL;q=q->next)
            if(q->data<min->data) 
                min=q;
        if(min!=p)
        {
            tmp=p->data;
            p->data=min->data;
            min->data=tmp;
        }
    }
    return head;
}

List *creat()//建立链表以负数结束
{
    printf("请输入创建链表结点值,以-1结束\n"); 
    List *head=NULL,*p1,*p2;
    p1=p2=(List*)malloc(LEN);
    scanf("%d",&p1->data);
    while(p1->data>=0)
    {
        if(head==NULL)head=p1;
        else p2->next=p1;
        p2=p1;
        p1=(List*)malloc(LEN);
        scanf("%d",&p1->data);
    }
    p2->next=NULL;
    return head;
}

void print(List *head)//输出链表 
{
    List *p=head;
    if(head==NULL)return;
    while(p)
    {
        printf("%4d->",p->data);
        p=p->next;
    }
    printf(" end.\n");
}

List *merge(List *h1,List *h2)// 合并两个有序链表 
{
    if(h1==NULL) return h2;
    if(h2==NULL) return h1;
    List *p1=h1,*p2=h2,*head=NULL;
    if(p1->data > p2->data)//先确定头结点
    {
        head=p2;
        p2=p2->next;
    }
    else
    {
        head=p1;
        p1=p1->next;
    }
    List *current=head;//current始终指向head链表的最后一个节点
    while(p1!=NULL && p2!=NULL) 
    {
        if(p1->data >p2->data)
        {
            current->next=p2;
            current=p2;
            p2=p2->next;
        }
        else
        {
            current->next=p1;
            current=p1;
            p1=p1->next;
        }
    }
    if(p1==NULL)//p1链表为空,就把剩下的p2链表直接加入head末尾
        current->next=p2;
    if(p2==NULL)
        current->next=p1;
    return head;
}
int main()
{
    List *h1,*h2,*head;
    printf("请创建链表1和链表2:");
    h1=selectsort(creat(h1));
    h2=selectsort(creat(h2));
    printf("排序结果:\n");
    print(h1);print(h2);
    printf("两个链表合并后的结果:\n");
    head=merge(h1,h2);
    print(head);
}

运行结果:

猜你喜欢

转载自www.cnblogs.com/yanglike111/p/13201431.html