0
点赞
收藏
分享

微信扫一扫

2024 年高教社杯全国大学生数学建模竞赛C题—农作物的种植策略(讲解+代码+成品论文助攻,均已更新完毕)

小云晓云 2024-09-08 阅读 28

问题:

解答:
main.cpp

#include <iostream>
#include "Stack.h"
using namespace std;
const int MAX = 5;

int main()
{
	Stack st(MAX);
	Item item;
	for (int i = 0; i < MAX; i++)
	{
		cout << "请输入一个无符号长整数:";
		cin >> item;
		while (cin.get() != '\n')continue;
		if (st.push(item))
		{
			cout << item << "已经入栈!" << endl;
		}
		else
		{
			cout << "入栈失败!" << endl;
		}
	}
	Stack st_new(st);
	for (int i = 0; i < MAX; i++)
	{
		if (st_new.pop(item))
		{
			cout << item << "出栈成功!" << endl;
		}
		else
		{
			cout << "出栈失败!" << endl;
		}
	}
	cout << "Bye" << endl;

	return 0;
}

Stack.h

#pragma once
#include <iostream>
using namespace std;

typedef unsigned long Item;

class Stack
{
private:
	enum{MAX=10};
	Item* pitems;
	int size;
	int top;
public:
	Stack(int n = MAX);
	Stack(const Stack& st);
	~Stack();

	bool isempty()const;
	bool isfull()const;
	bool push(const Item& item);
	bool pop(Item& item);

	Stack& operator=(const Stack& st);
};


Stack.cpp

#include "Stack.h"

Stack::Stack(int n)
{
	size = n;
	pitems = new Item[size];
	top = 0;
}
Stack::Stack(const Stack& st)
{
	pitems = new Item[st.size];
	for (int i = 0; i < st.size; i++)
	{
		pitems[i] = st.pitems[i];
	}
	size = st.size;
	top = st.top;

}
Stack::~Stack()
{
	if (pitems)
	{
		delete[] pitems;
	}
}

bool Stack::isempty()const
{
	if (top == 0)
	{
		return true;
	}
	else
	{
		return false;
	}
}
bool Stack::isfull()const
{
	if (top == size)
	{
		return true;
	}
	else
	{
		return false;
	}
}
bool Stack::push(const Item& item)
{
	if (isfull())
	{
		cout << "栈已满,无法入栈!" << endl;
		return false;
	}
	pitems[top++] = item;
	return true;
}
bool Stack::pop(Item& item)
{
	if (isempty())
	{
		cout << "栈已空,无法出栈!" << endl;
		return false;
	}
	item = pitems[--top];
	return true;
}

Stack& Stack::operator=(const Stack& st)
{
	if (this == &st)
	{
		return *this;
	}
	if (pitems)delete[] pitems;

	pitems = new Item[st.size];
	for (int i = 0; i < size; i++)
	{
		pitems[i] = st.pitems[i];
	}
	size = st.size;
	top = st.top;
	return *this;
}

运行结果:
在这里插入图片描述

考查点:

  • 栈数据结构
  • 动态内存分配
  • 拷贝构造函数
  • 赋值构造函数
  • 析构

2024年9月8日10:58:48

举报

相关推荐

0 条评论