线性表基本操作和简单程序
建立两个数据域定义为整型的单链表,两个链表的数据域已按升序排序,将两个有序链表合并成一个新的无重复元素的有序链表,最后可以根据输入的数据,找到相应的结点,后删除之。
(考察线性表的基本操作:初始化、插入、删除、取数据元素等运算在链表存储结构上的程序设计方法)
代码如下所示:
#include<stdio.h>
#include<stdlib.h>
typedef struct node
{
int data;
struct node *next;
}node;
node*creat(node *head)//创建链表
{
int i,n,a[20];
struct node *s,*k;
printf("please input the length of the Lb list you want toinput:");
scanf("%d",&n);
head=(node*)malloc(sizeof(node));
k=head;
for(i=0;i<n;i++)
{
s=(node*)malloc(sizeof(node));
printf("pleaseinput %d node value",i+1);
scanf("%d",&a[i]);
s->data=a[i];
k->next=s;
k=s;
}
k->next=NULL;
return head;
}
node *combine(node *La,node*Lb)//合并链表
{
node *pa,*pb;
pa=La->next;
pb=Lb->next;
while(pa&&pb){
if(pa->data>pb->data){
La->next=pb;
La=pb;
pb=pb->next;
}
else{
if(pa->data==pb->data){
La->next=pa;
La=pa;
pa=pa->next;
pb=pb->next;
}
else{
La->next=pa;
La=pa;
pa=pa->next;
}
}
}
if(pa!=NULL) La->next=pa;
else La->next=pb;
}
node *Delete(node *head,inti)//删除指定结点
{
node *p,*q;
p=head->next;
while(p)
{
if((p->next)->data==i)
{
q=p->next;
p->next=q->next;
free(q);
break;
}
p=p->next;
}
return head;
}
void show(node *L){//输出带头结点的单链表L中的各个结点的值
struct node *p;
for(p=L->next;p!=NULL;p=p->next)printf("%d ",p->data);
printf("\n");
}
int main()
{
int m;
struct node *La,*Lb,*L;
La=creat(L);
show(La);
Lb=creat(L);
show(Lb);
combine(La,Lb);//合并后新链表尾La
printf("the combined list is:");
show(La);
printf("please input the node you want to delete:");
scanf("%d",&m);
Delete(La,m);
printf("the deleted linked list is:");
show(La);
return 0;
}