带最小值操作的栈 c++实现

#include<iostream>

using namespace std;

class Stack
{
public:
	Stack();
	~Stack();

private:
	typedef struct Node
	{
		struct Node *P;
		int x;
	}*BitNode,BitValue;

	BitNode Start;
	BitNode Min_Start;

public:
	void push(int x);
	void pop(int *x,int*y);
	int getMin();

	
};

Stack::Stack()
{
	Start = (BitNode)malloc(sizeof(BitValue));
	Min_Start = (BitNode)malloc(sizeof(BitValue));
	Start->P = NULL;
	Min_Start->P = NULL;
}

Stack::~Stack()
{
	BitNode ST;
	BitNode Min_ST;

	ST = Start->P;
	while (!ST)
	{
		Start->P = ST->P;
		free(ST);
		ST = Start->P;
	}
	free(Start);

	Min_ST = Min_Start->P;
	while (!Min_ST)
	{
		Min_Start->P = Min_ST->P;
		free(Min_ST);
		Min_ST = Min_Start->P;
	}
	free(Min_Start);
}

void Stack::push(int num)
{
	BitNode Start_Input;
	BitNode Min_Start_Input;
	Start_Input = (BitNode)malloc(sizeof(BitValue));
	Min_Start_Input = (BitNode)malloc(sizeof(BitValue));
	Start_Input->x = num;
	Start_Input->P = Start->P;
	Start->P = Start_Input;
	if (Min_Start->P != 0)
	{
		int return_num = Min_Start->P->x;
		if (num < return_num)
			Min_Start_Input->x = num;
		else
			Min_Start_Input->x = return_num;
	}
	else
	{
		Min_Start_Input->x = num;
	}
	
	Min_Start_Input->P = Min_Start->P;
	Min_Start->P = Min_Start_Input;
}

int Stack::getMin()
{
	return Min_Start->P->x;
}

void Stack::pop(int *x,int *y)
{
	*x = Start->P->x;
	*y = Min_Start->P->x;
	
	BitNode pop_Start;
	BitNode pop_Min_Start;
	pop_Start = Start->P;
	pop_Min_Start = Min_Start->P;
	Start->P = Start->P->P;
	Min_Start->P = Min_Start->P->P;
	free(pop_Start);
	free(pop_Min_Start);		
}

void main()
{
	Stack it;
	int x;
	int y;
	it.push(58);
	it.push(8);
	it.push(7);
	it.push(18);
	it.push(28);
	it.push(58);
	it.pop(&x, &y);
	cout << x << endl;
	cout << y << endl;
	
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值