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

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

程序:

#include
using namespace std;

int main()
{
	//链表的实现

	struct Polynomial		//定义结构体数组
	{
		int degree;			//多项式的次数
		double coefficient;			//多项式的系数
		struct Polynomial *next;		//后继指针
	};
	Polynomial head;			//头结点
	Polynomial *p;				//用于各种操作的临时指针
	int length_of_linear_list = 0;			//记录链表的长度
	head.next = NULL;
	int temp_degree;		//用来判断是否继续输入
	double temp_coefficient;
	cout << "enter coefficient and degree ,enter -1,-1 for end  " << endl;
	while(true)
	{
		p = new struct Polynomial();			//创建新结点
		cin >> temp_coefficient >> temp_degree;		//输入
		if (temp_degree < 0)break;
		p->coefficient = temp_coefficient;
		p->degree = temp_degree;
		p->next = head.next;			//在头结点和第一个结点之间插入刚刚申请的这个结点
		head.next = p;
		length_of_linear_list++;
	}
	p = head.next;
	cout << "the polynomial is   ";
	while (p != NULL)
	{
		if (p != head.next)cout << " + ";
		cout << p->coefficient << "*x^" << p->degree;		//输出
		p = p->next;			//指针后移
	}

	//插入操作
	int i;				//在第i个元素之前插入1个元素
	cout << endl << endl << "在第i个元素之前插入1个元素,输入i    ";
	cin >> i;
	if (i<1 || i>length_of_linear_list)cout << "enter error!";
	else
	{
		int position = 0;			//记录指针p目前的位置
		Polynomial *insert;
		insert = new struct Polynomial();			//申请新结点
		cout << endl << "enter what you what to insert    ";
		cin >> insert->coefficient >> insert->degree;		//输入
		p = &head;
		while (p != NULL && position< i - 1)		//将p定位到i-1的位置
		{
			p = p->next;
			position++;
		}
		insert->next = p->next;		//在p和p的后继之间插入刚刚申请的insert
		p->next = insert;
		p = head.next;
		cout << "the polynomial is   ";
		while (p != NULL)
		{
			if (p != head.next)cout << " + ";
			cout << p->coefficient << "*x^" << p->degree;		//输出
			p = p->next;			//指针后移
		}
	}

	//删除操作
	int i2;				//删除第i2个元素
	cout << endl << endl << "删除第i个元素,输入i   ";
	cin >> i2;
	if (i2<1 || i2>length_of_linear_list)cout << "enter error!";
	else
	{
		int position = 0;			//记录指针p目前的位置
		p = &head;
		while (p != NULL && position< i2 - 1)		//将p定位到i-1的位置
		{
			p = p->next;
			position++;
		}
		Polynomial *temp;		//用temp保存要删掉的结点
		temp = p->next;
		p->next = temp->next;
		free(temp);
	}
	p = head.next;
	cout << "the polynomial is   ";
	while (p != NULL)
	{
		if (p != head.next)cout << " + ";
		cout << p->coefficient << "*x^" << p->degree;		//输出
		p = p->next;			//指针后移
	}

	//查找操作
	int number_find;
	cout << endl << endl << "enter the number you find" << "   ";
	cin >> number_find;
	p = head.next;
	int position = 1;			//记录指针p目前的位置
	while (p->degree != number_find)
	{
		p = p->next;
		position++;
	}
	cout << number_find << "是第" << position << "个元素";
	return 0;
}

运行结果:

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

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