数据结构实验1《线性表的操作》(1)

(1)顺序表的创建、插入、删除、查找,以及线性表合并

程序:

#include
using namespace std;

int main()

{
	//顺序表的实现
	struct linear_list_polynomial//定义结构体数组
	{
		int degree;//多项式的次数
		double coefficient;//多项式的系数
	};

	int max_degree;
	cout << "enter the max_degree" << endl;
	cin >> max_degree;//max_degree是最大次数,分配max_degree这么多空间
	cout << "enter degree and coefficient , enter -1,-1 for end" << endl;
	struct linear_list_polynomial *pointer = new struct linear_list_polynomial[max_degree];
	int length_of_linear_list = 0;//记录链表的长度
	for (int i = 0; i < max_degree; i++)//输入,初始化

	{
		cin >> pointer[i].degree >> pointer[i].coefficient;
		if (pointer[i].degree == -1)break;
		length_of_linear_list++;
	}
	cout << "the linear list is" << endl;
	for (int i = 0; i < length_of_linear_list; i++)//输出
		cout << pointer[i].degree << " " << pointer[i].coefficient << "     ";

	//插入操作
	int i;//在第i个元素之前插入1个元素
	cout << endl << endl << "在第i个元素之前插入1个元素,输入i" << endl;
	cin >> i;
	if (i<1 || i>length_of_linear_list)cout << "enter error!";
	else
	{
		for (int j = length_of_linear_list; j>i - 2; j--)
			pointer[j + 1] = pointer[j];
		cout << "enter what you what to insert" << endl;
		cin >> pointer[i - 1].degree >> pointer[i - 1].coefficient;
		length_of_linear_list++;
		for (int i = 0; i < length_of_linear_list; i++)//输出
			cout << pointer[i].degree << " " << pointer[i].coefficient << "     ";
	}

	//删除操作
	int i2;//删除第i2个元素
	cout << endl << endl << "删除第i个元素,输入i" << endl;
	cin >> i2;
	if (i2<1 || i2>length_of_linear_list)
		cout << "enter error!";
	else
	{
		for (int j = i2; j<length_of_linear_list; j++)
			pointer[j - 1] = pointer[j];
		length_of_linear_list--;
		for (int i = 0; i < length_of_linear_list; i++)//输出
			cout << pointer[i].degree << " " << pointer[i].coefficient << "     ";
	}

	//查找操作
	int number_find;
	cout << endl << endl << "enter the number you find" << "   ";
	cin >> number_find;
	for (int i = 0; i < length_of_linear_list; i++)//输出
	{
		if (pointer[i].degree == number_find)
		{
			cout << number_find << "是第" << i + 1 << "个元素";
			break;
		}
	}
	return 0;
}
运行结果:

数据结构实验1《线性表的操作》(1)_第1张图片



你可能感兴趣的:(数据结构实验1《线性表的操作》(1))