作业二之合并链表

来源:互联网 发布:古城数据 编辑:程序博客网 时间:2024/06/05 06:32

#include<stdio.h>//链表没有长度的限制

#include<malloc.h>

typedef struct node

{

int data;

struct node* next;

}Node,*Lnode;//定义结点

void insert(Lnode head)  //插入数据

{

int i;

Lnode q;             //定义全局变量q,用q来辅助构造链表

for(i=0;i<3;i++)

{

Lnode p=(Lnode)malloc(sizeof(Node));//创建新结点

printf("please input the num: ");

scanf("%d",&(p->data));

if(head->next==NULL)

{

head->next=p;

p->next=NULL;

q=head->next;

}

else

{

q->next=p;

p->next=NULL;

q=p;

}

}

}

void print(Lnode head)

{

int i;

Lnode p=head->next;//指向第一个结点

for(i=0;i<6;i++)

{

printf("%d ",p->data);

p=p->next;

}

}

 

void unite(Lnode *head1,Lnode *head2,Lnode *lc)//如果有2个'*',就是&head,一个就直接是head

{

Lnode p1,p2,p3,p4,p5;

int i,j;

p1=*head1;//指向头结点

p2=*head2;

p3=p1->next;//指向第一个结点

p4=p2->next;

p5=*lc=*head1;

for(;p3&&p4;)

{

if(p3->data<=p4->data) {p5->next=p3;p5=p3;p3=p3->next;}

else {p5->next=p4;p5=p4;p4=p4->next;}

}

p5->next=p3?p3:p4;

}

void main()//合并链表千万不要怕设置参数,可以多设几个参数来进行合并

{

Lnode head1,head2,head3;

int i,j;

head1=(Lnode)malloc(sizeof(Node));

head1->next=NULL;//创建空链表

head2=(Lnode)malloc(sizeof(Node));

head2->next=NULL;

head3=(Lnode)malloc(sizeof(Node));

head3->next=NULL;

printf("init head1 /n");

insert(head1);

printf("init head2 /n");

insert(head2);

unite(&head1,&head2,&head3);

print(head3);

 

}

原创粉丝点击