合并两个线性表c 语言,如何用c程序建立两个线性表并把他们合并成一个线性表?...

满意答案

《合并两个线性表c 语言,如何用c程序建立两个线性表并把他们合并成一个线性表?...》

ryan_gan

推荐于 2017.11.23

《合并两个线性表c 语言,如何用c程序建立两个线性表并把他们合并成一个线性表?...》

采纳率:52%    等级:12

已帮助:14275人

从键盘输入两个链表,通过程序对他们排序,之后按递增顺序合并链表

#include “stdio.h”

#include “stdlib.h”

#include “malloc.h”

#define NULL 0

struct List

{

int data;

struct List *next;

}List;

struct List * InitList()

{

struct List *head,*p,*q;

int d;

head=(struct List *)malloc(sizeof(struct List));

head->next=NULL;

p=head;

scanf(“%d”,&d);

while(d>0)

{

q=(struct List *)malloc(sizeof(struct List));

q->next=NULL;

q->data=d;

p->next=q;

p=p->next;

scanf(“%d”,&d);

}

return head;

}

void ListChooseSort(struct List *head)

{

struct List *p,*q;

int t;

if(head->next!=NULL)

{

for(p=head->next;p->next;p=p->next)

for(q=p->next;q;q=q->next)

if(q->datadata)

{

t=p->data;

p->data=q->data;

q->data=t;

}

}

}

struct List * UniteList(struct List *a,struct List *b)

{

struct List *U_head,*p,*q,*s;

U_head=(struct List *)malloc(sizeof(struct List));

U_head->next=NULL;

p=a->next;

q=b->next;

s=U_head;

while(p&&q)

{

if(p->data>q->data)

{

s->next=q;

q=q->next;

}

else

{

s->next=p;

p=p->next;

}

s=s->next;

}

if(p==NULL)s->next=q;

else s->next=p;

return U_head;

}

void ListPrint(struct List *head)

{

struct List *p;

p=head->next;

printf(“\n\n”);

while(p)

{

printf(“%5d”,p->data);

p=p->next;

}

printf(“\n\n”);

}

void main ()

{

struct List *a_head,*b_head,*Unite_head;

printf(“\n创建链表a:\n\n”);

a_head=InitList();

printf(“\n链表a:”);

ListPrint(a_head);

system(“pause”);

system(“cls”);

printf(“\n创建链表b:\n\n”);

b_head=InitList();

printf(“\n链表b:”);

ListPrint(b_head);

system(“pause”);

system(“cls”);

ListChooseSort(a_head);

printf(“\n递增排序后的链表a:”);

ListPrint(a_head);

ListChooseSort(b_head);

printf(“递增排序后的链表b:”);

ListPrint(b_head);

Unite_head=UniteList(a_head,b_head);

printf(“合并后的链表为:”);

ListPrint(Unite_head);

}

00分享举报

    原文作者:握中悬璧
    原文地址: https://blog.csdn.net/weixin_34725044/article/details/117191105
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞