关闭

数据结构 线性表 顺序表的归并 无序版

358人阅读 评论(0) 收藏 举报
#include <stdio.h>
#include <stdlib.h>

#define LIST_INIT_SIZE    100
#define LISTLNCREMENT     10
#define OK                1
#define ERROR             0
#define OVERFLOW          -2

typedef int ElemType;

typedef struct
{
	ElemType *elem;
	int length;
	int listsize;
}SqList;


int InitList_Sq(SqList &L)
{
	L.elem = (ElemType *) malloc(LIST_INIT_SIZE * sizeof(ElemType));
	if (!L.elem)
	{
		exit(OVERFLOW);
	}
	L.length = 0;
	L.listsize = LIST_INIT_SIZE;
	return OK;
}

void Create_Sq(SqList &L, int n)
{
	int i;
	for (i=0; i<n; i++)
	{
		scanf("%d",&L.elem[i]);
	}
	L.length = n;
}

void Display_Sq(SqList L)
{
	int i;
	for (i=0; i<L.length ; i++)
	{
		printf("%d ",L.elem[i]);
	}
	printf("\n");
}

int Find(SqList L, ElemType e)
{
	int i = 0;
	while (i<L.length)
	{
		if (L.elem[i] == e)
		{
			break;
		}
		++i;
	}
	if (i == L.length)
	{
		return 0;
	}
	return 1;
}


int ListInsert_Sq(SqList &L, int i, ElemType e)
{
	ElemType *newbase,*p,*q;
	if (i<1 || i>L.length+1)
	{
		return ERROR;
	}
	if (L.length >= L.listsize)
	{
		newbase = (ElemType *)realloc(L.elem ,(L.listsize + LISTLNCREMENT) * sizeof(LISTLNCREMENT));
		if (!newbase)
		{
			exit(OVERFLOW);
		}
		L.elem = newbase;
		L.listsize += LISTLNCREMENT;
	}
	q = &(L.elem [i-1]);
	for (p=&(L.elem[L.length-1]);p>=q;--p)
	{
		*(p+1) = *p;
	}
	*q = e;
	++L.length ;
	return OK;
}

int GetData(SqList L,int i)
{
	if (i<1 || i>L.length+1)
	{
		return ERROR;
	}
	else
		return L.elem[i-1];
}

void MergeList_Sq(SqList &La, SqList Lb)
{
	int i,e;
	int n = La.length + 1 ;
	int m = Lb.length ;
	for (i=1; i<=m; i++)
	{
		e = GetData(Lb,i);
		if (!Find(La,Lb.elem[i-1]))
		{
			ListInsert_Sq(La,n,e);
			++n;
		}
	}
}

int main()
{
	int n;
	SqList La,Lb;
	InitList_Sq(La);
	InitList_Sq(Lb);
	printf("请输入链表La的长度: ");
	scanf("%d",&n);
	printf("请输入 %d 个数据: ",n);
	Create_Sq(La,n);
	printf("请输入链表Lb的长度: ");
	scanf("%d",&n);
	printf("请输入 %d 个数据: ",n);
	Create_Sq(Lb,n);
	MergeList_Sq(La,Lb);
	printf("两个链表归并后的链表是: ");
	Display_Sq(La);
	return 0;
}

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:113145次
    • 积分:3868
    • 等级:
    • 排名:第8223名
    • 原创:293篇
    • 转载:0篇
    • 译文:0篇
    • 评论:14条
    文章分类
    最新评论