顺序表基本操作

记录简单的顺序表操作

#include "List.h"
#include <stdlib.h>
#include <iostream>


void CreateList(SqList *&L, ElemType a[], int n) {
	int i;
	L = (SqList *)malloc(sizeof(SqList));
	for (i = 0; i < n; i++) 
		L->data[i] = a[i];
	L->length = n;
}

void InitList(SqList *&L) {
	L = (SqList *)malloc(sizeof(SqList));
	L->length = 0;
}

void DestroyList(SqList *&L) {
	free(L);
}

bool ListEmpty(SqList *L) {
	return (L->length == 0);
}

int ListLength(SqList *L) {
	return (L->length);
}

void DispList(SqList *L) {
	int i;
	for (i = 0; i < L->length; i++) {
		std::cout << L->data[i] << " ";
	}
}

bool GetElem(SqList *L, int i, ElemType &e) {
	if (i <1 || i >L->length)
		return false;
	e = L->data[i - 1];
	return true;
}

int LocateElem(SqList *L, ElemType e) {
	int i = 0;
	while (i < L->length && L->data[i] != e)
		i++;
	if (i >= L->length)
		return 0;
	else
		return i + 1;
}

bool ListInsert(SqList *&L, int i, ElemType e) {
	int j;
	if (i < 1 || i > L->length + 1)
		return false;
	i--;
	for (j = L->length; j > i; j--)
		L->data[j] = L->data[j - 1];
	L->data[i] = e;
	L->length += 1;
	return true;
}
bool listDelete(SqList *&L, int i, ElemType &e) {
	int j;
	if (i < 1 || i>L->length)
		return false;
	i--;
	e = L->data[i];
	for (j = i; j < L->length - 1; j++)
		L->data[j] = L->data[j + 1];
	L->length -= 1;
	return true;
}


void unionList(SqList *LA, SqList *LB, SqList *&LC) {
	int lena, i;
	ElemType e;
	InitList(LC);
	for (i = 1; i <= ListLength(LA); i++) {
		GetElem(LA, i, e);
		ListInsert(LC, i, e);
	}
	lena = ListLength(LA);
	for (i = 1; i <= ListLength(LB); i++) {
		GetElem(LB, i, e);
		if (!LocateElem(LA, e))
			ListInsert(LC, ++lena, e);
	}
}

  

 1 #include <iostream>
 2 #include "List.h"
 3 using namespace std;
 4 
 5 int main() {
 6 
 7     SqList *A, *B, *C;
 8     InitList(A);
 9     InitList(B);
10     const int m = 5, n = 10;
11     int a[n];
12     int b[m];
13     cout << "Input 10 numbers for list A" << endl;
14     for (int i = 0; i < n; i++) {
15         cin >> a[i];
16     }
17     
18     CreateList(A, a, 10);
19     cout << "ListA:" << endl;
20     DispList(A);
21 
22     cout << endl<<"Input 5 numbers for list B" << endl;
23     for (int i = 0; i < m; i++) {
24         cin >> b[i];
25     }
26     CreateList(B, b, 5);
27     cout << "ListB:" << endl;
28     DispList(B);
29     cout << endl;
30     unionList(A, B, C);
31     cout << "ListC:" << endl;
32     DispList(C);
33 
34     system("pause");
35 }

 

 

 

 

转载于:https://www.cnblogs.com/Arvin-JIN/p/8974856.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值