/************************************/
/* 单链表表检索用的头文件 */
/* 文件名:linklist.h */
/************************************/
#include <stdlib.h>
#include <stdio.h>
typedef int datatype;
typedef struct node
{
datatype data;
struct node *next;
}linknode;
typedef linknode *linklist;
/*头插法建立单链表*/
linklist creat1()
{
linklist head,s;
int x;
head=(linklist)malloc(sizeof(linknode));
head->next=NULL;
printf("Input some integer data:\n");
scanf("%d",&x);
/*补充完整*/
while (x!=0)
{
s=(linklist)malloc(sizeof(linknode));
s->data=x;
s->next=head->next;
head->next=s;
scanf("%d",&x);
}
return head;
}
/*尾插法建立带头结点的单链表*/
linklist creat2()
{
linklist head,r,s;
int x;
head=r=(linklist)malloc(sizeof(linknode));
head->next=NULL;
printf("Input some integer data:\n");
scanf("%d",&x);
/*补充完整*/
while (x!=0)
{
s=(linklist)malloc(sizeof(linknode));
s->data=x;
r->next=s;
r=s;
scanf("%d",&x);
}
r->next=NULL;
return head;
}
/******尾插法建立不带头结点的循环单链表****/
linklist creat3(int n)
{
linklist head,r,s;
datatype i=0;
head=r=NULL;
//printf("Input some integer data:\n");
//scanf("%d",&x);
while (i<n)
{
s=(linklist)malloc(sizeof(linknode));
s->data=++i;
if (head==NULL)
head=s;
else
r->next=s;
r=s;
//scanf("%d",&x);
}
if (r) r->next=head;
return head;
}
/***输出不带头节点的单链表****/
void print2(linklist head)
{
linklist p;
p=head;
printf("List is:\n");
//printf("%5d",p->data);
while(p->next!=head)
{
printf("%5d",p->data);
p=p->next;
}
printf("%5d",p->data); //输出最后一个节点数
printf("\n");
}
/*输出带头结点的单链表*/
void print(linklist head)
{
linklist p;
p=head->next;
printf("List is:\n");
while(p)
{
printf("%5d",p->data);
p=p->next;
}
printf("\n");
}
/*释放单链表的内容*/
void delList(linklist head)
{
linklist p=head;
while (p)
{
head=p->next;
free(p);
p=head;
}
}
/*将升序链表head1和升序链表head2求他们的并集合到head2中*/
#include "linklist.h"
linklist bing(linklist head1,linklist head2)
{
linklist p1=head1->next,p2=head2->next,pre2=head2,s1=NULL,t=NULL;
head1->next=NULL;
while(p1)
{
s1=p1;
p1=p1->next;
s1->next=NULL;
while(p2&&p2->data<=s1->data)
{
pre2=p2;
p2=p2->next;
}
if(p2!=NULL)//找到了p2->next>s1->data
{
s1->next=pre2->next;
pre2->next=s1;
//s1=pre2;
}
if(p2==NULL)
{
pre2->next=s1;
pre2=s1;
s1->next=p1;
}
}
return head2;
}
main()
{
linklist head1,head2,head3,x;
head1=creat2(); /*尾插法建立单链表*/
print(head1);
head2=creat2();
print(head2);
//head3=creat2();
//print(head3);
printf("合并后的链表为:");
x=bing(head1,head2);
print(x);
}
会有重复的数,怎么改,并集中时不允许出现相同数字的,是那出问题,或者那没有考虑到呢?请高手指教
不胜感激