1. 程式人生 > >資料結構——商品貨架管理(C++實現) 原始碼

資料結構——商品貨架管理(C++實現) 原始碼

*尚品貨架可以看成一個棧,棧頂商品的生產日期最早,棧底商品的生產日期最近。 *上貨時,需要倒貨架,以保證生產日期較新的商品在較靠裡的位置  

針對一種特定商品,實現上述管理過程

測試資料:由學生自己確定一組測試資料。注意測試邊界資料,如空棧。

原始碼

#include <iostream>
using namespace std;

struct stack{  //定義一個棧
	int* Slist;
	int top;
	int Maxsize;
};
void Initstack(stack&SL, const int MS); //棧初始化
bool Stackempty(stack&SL);//判棧空
bool Stackfull(stack&SL); //棧滿
void Clearstack(stack&SL); //清空棧
int Push(stack&SL, int&item);//新元素推進棧
int Pop(stack&SL);//出棧
void Traverstack(stack&SL); //輸出棧中元素



void Initstack(stack&SL, const int MS) //棧的初始化
{
	SL.Slist = new int[MS];
	if (!SL.Slist){
		cout << "給棧分配記憶體失敗。" << endl;
		exit(1);
	}
	SL.Maxsize = MS; 
	SL.top = -1;
}
bool Stackempty(stack&SL) //判空
{
	return SL.top == -1;
}
bool Stackfull(stack&SL)//判滿
{
	return SL.top == SL.Maxsize;
}
void Clearstack(stack&SL)//清空棧
{
	SL.top = -1;
}
int Push(stack&SL, int&item)//元素進棧
{
	if (Stackfull(SL)) return false;
	SL.top++;
	SL.Slist[SL.top] = item;
	return SL.Slist[SL.top];
}
int Pop(stack&SL) //元素出棧
{
	if (Stackempty(SL)) return false;
	return SL.Slist[SL.top--];
	SL.top--;
}
void Traverstack(stack&SL)//輸出棧
{
	for (int i = 0; i <= SL.top; i++)
		cout << SL.Slist[i] << endl;
	cout << endl;
}




const int N =5;//預設棧的最大空間
void main(){
	cout << "***************商品貨架管理****************" << endl;

	int i, t, temp, x; 
	stack s;	
	Initstack(s, N);
	cout << "輸入貨架上的現有的商品資訊:" << endl;
	cout << "注:從最裡端開始(即日期較大),預設貨架有五個商品可放空間,輸入五組資料,每個商品日期以回車鍵結束輸入" << endl;
	for (i = 0; i<N ;i++) { //輸入5個日期
		cin >> x;
		Push(s,x);
	}
	cout << "***************商品錄入完畢****************" << endl;
	
	cout << "請輸入要取商品的數量:" << endl;
	cin >> x;
	while (x<0 && x>N){
		cout << "要求的商品數量不合理,請重新輸入:" << endl;
		cin >> x;
	}
	for (i = 0; i<x; i++) //取x件商品
		cout << "取出的商品生產日期有:" << Pop(s) << endl;
	t = s.Maxsize - s.top -1;
	cout << "現在貨架還能放下" << t << "件商品" << endl;
	
	stack s1;//建立輔助棧
	Initstack(s1, N);
	cout << "請輸入要放入貨架的新商品日期:" << endl;
	for(i=0;i<t;i++){//倒貨操作
		cin>>x;
		while(Stackempty(s)!=1&&x>s.Slist[s.top]){
			temp=Pop(s);
			Push(s1,temp);
		}
		Push(s,x);
		while(Stackempty(s1)!=1){
			temp=Pop(s1);
			Push(s,temp);
		}
	}
	cout << "***************商品上貨完畢****************" << endl;
	cout << "從貨架靠裡端到外端的商品的日期為:" << endl;
	Traverstack(s); // 顯示放入新商品後棧元素順序

}
       

執行示例