#include<stdio.h>
#include<stdlib.h>
#define Status int
//数据类型
typedef struct
{
int number;
}ElemType;
//结点类型
typedef struct LNode
{
LNode *next;
ElemType data;
int Length;
}LNode, *LinkList;
//初始化链表
Status InitList(LinkList &L)
{
if(!L)
{
L = (LNode *)malloc(sizeof(LNode));
if(!L) return 0;
L->next = NULL;
L->Length = 0;
return 1;
}
return 0;
}
//插入结点
Status InsertElem(LinkList &L, int i, ElemType e)
{
LNode *p;
int j = 0;
p = L;
while(p && j<i-1)
{
p = p->next;
j++;
}
if(!p || i<=0) return 0;
LNode *s = (LNode *)malloc(sizeof(LNode));
s->data = e;
s->next = NULL;
s->next = p->next;
p->next = s;
L->Length++;
return 1;
}
//删除结点
Status DeleteElem(LinkList &L, int i, ElemType &e)
{
LNode *p,*q;
int j=0;
p = L;
while(p && j<i-1)
{
p = p->next;
j++;
}
if(!p || i<=0) return 0;
q = p->next;
p->next = q->next;
e = q->data;
free(q);
L->Length--;
return 1;
}
//查找结点
Status LocateList(LinkList L, ElemType e)
{
if(!L)
return 0;
int i = 0;
LNode *p;
p = L;
while(p)
{
if(p->data.number != e.number)
{
p = p->next;
i++;
}
else
break;
}
if(!p) return 0;
return i;
}
//返回结点
Status GetElem(LinkList L, int i,ElemType &e)
{
int j=0;
LNode *p = L;
while(p && j<i)
{
p = p->next;
j++;
}
if(!p || i<=0)
{
return 0;
}
e = p->data;
return e.number;
}
//销毁链表
Status DestroyList(LinkList &L)
{
if(!L)
return 0;
LNode *p, *q;
p = L;
while(p)
{
q = p->next;
free(p);
p = q;
}
return 1;
}
//合并有序链表
Status MergeList(LinkList La, LinkList Lb, LinkList &Lc)
{
LNode *p1 = La->next;
LNode *p2 = Lb->next;
LNode *p3;
Lc = La;
p3 = Lc;
while(p1 && p2)
{
if(p1->data.number <= p2->data.number)
{
p3->next = p1;
p3 = p1;
p1 = p1->next;
}
else
{
p3->next = p2;
p3 = p2;
p2 = p2->next;
}
}
if(p1)
p3->next = p1;
else
p3->next = p2;
free(Lb);
return 1;
}
//主函数
void main()
{
int i, num;
ElemType e;
LinkList La = NULL;
InitList(La);
LinkList Lb = NULL;
InitList(Lb);
LinkList Lc;
printf("定义La\n");
for(i=1;i<4;i++)
{
scanf("%d",&num);
e.number = num;
InsertElem(La,i,e);
}
printf("定义Lb\n");
for(i=1;i<4;i++)
{
scanf("%d",&num);
e.number = num;
InsertElem(Lb,i,e);
}
printf("合并有序链表\n");
MergeList(La,Lb,Lc);
for(i=1;i<7;i++)
{
printf("Lc中第%d个是%d\n",i,GetElem(Lc,i,e));
}
printf("\n");
if(DestroyList(Lc))
printf("删除链表Lc成功!\n");
}
【数据结构-C语言实现】合并有序链表
最新推荐文章于 2024-08-20 15:47:23 发布