顺序表

本文详细介绍了使用C++实现静态和动态数组列表的基本操作,包括初始化、添加元素、删除元素和打印列表。通过具体代码示例,展示了如何进行数组列表的创建、元素的插入和删除等常见操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <iostream>
#include <stdlib.h>
#pragma warning(disable:4996)

#define MaxSize 100

typedef int Elemtype;
typedef struct SqList
{
	Elemtype data[MaxSize];
	int length;

	void init() {
		this->length = 0;
	}

	bool append(Elemtype e)
	{
		if (this->length+1 > MaxSize)
			return false;
		else
		{
			this->data[length] = e;
			this->length++;
			return true;
		}
	}

	bool add(int index, Elemtype e)
	{
		if (index > this->length || this->length+1 > MaxSize)
			return false;
		else
		{
			for (int i = length; i >= index-1; i--)
			{
				this->data[i] = this->data[i - 1];
			}
			this->data[index - 1] = e;
			this->length++;
			return true;
		}
	}

	bool del(int index,Elemtype &e)
	{
		if (index > length)
			return false;
		else
		{ 
			e = this->data[index - 1];
			for (int i = index; i < this->length; i++)
			{
				this->data[i - 1] = this->data[i];
			}
			this->length--;
		}
		return true;
	}
}SqList;

typedef struct SeqList 
{
	Elemtype *data;
	int length, Max;

	void init() {
		this->length = 0;
	}
}SeqList;

SqList createSqList()
{
	SqList L;
	L.init();
	int x;
	scanf("%d", &x);
	for (int i = 0; i < MaxSize; i++)
	{
		if (x != 999)
		{
			L.data[i] = x;
			L.length++;
			scanf("%d", &x);
		}
		else
			return L;
	}
	return L;
}
//动态创建
SeqList createSeqList(int len)
{
	SeqList SL;
	SL.data = (Elemtype*)malloc(sizeof(Elemtype)*len);
	SL.init();
	SL.Max = len;
	int x;
	scanf("%d", &x);
	for (int i = 0; i < len; i++)
	{
		if (x != 999)
		{
			SL.data[i] = x;
			SL.length++;
			scanf("%d", &x);
		}
		else
			return SL;
	}
	return SL;
}

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

void PrintList(SeqList SL)
{
	for (int i = 0; i < SL.length; i++)
	{
		printf("%4d", SL.data[i]);
	}
	printf("\n");
}


int main(int agrc, char **argv)
{
#if 0

	SqList L;
	L.init();
	L.append(1);
	L.append(2);
	L.add(2, 3);
	int x;
	L.del(2, x);
	PrintList(L);
	printf("%4d\n", x);

#endif // 0

#if 0

	SqList L = createSqList();
	PrintList(L);
	L.append(36);
	PrintList(L);
	L.add(2, 0);
	PrintList(L);
	int x;
	L.del(3, x);
	PrintList(L);
	printf("%4d", x);

#endif // 0

	SeqList SL = createSeqList(5);
	PrintList(SL);
	
	system("pause");
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值