数组栈的实现(C++)

栈的属性为先进后出,后进先出;故只能通过栈顶删除和插入;

实现方法如下:

Stack.h:

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

class Stack
{
public:	int* a;
	int top;
	int capacity;
};//栈类

void StackInit(Stack*ps);//栈初始化
void StackPop(Stack* ps);//栈顶删除
void StackPush(Stack* ps,int x);//栈顶插入
int StackTop(Stack* ps);//栈顶数
int StackSize(Stack* ps);//栈大小
bool Stackempty(Stack* ps);//是否为空

Stack.cpp:

#include"stack.h"
using namespace std;

void StackInit(Stack* ps)
{
	if (ps == NULL)
	{
		return;
	}
	ps->a = NULL;
	ps->capacity = 0;
	ps->top = 0;
}

void StackPop(Stack* ps)
{
	ps->top--;
	ps->a[ps->top] = NULL;
}
void StackPush(Stack* ps,int x)
{
	if (ps == NULL)
	{
		return;
	}
	else if (ps->capacity == ps->top)
	{
		int newcapacity;
		if (ps->capacity == 0)
		{
			newcapacity = 4;
		}
		else
		{
			newcapacity = 2*ps->capacity;
		}
		ps->capacity = newcapacity;
		int* temp = new int[newcapacity];
		
		for (int i = ps->top;i > 0;i--)
		{
			temp[i - 1] = ps->a[i - 1];
		}
		
		
		ps->a = temp;
		
	}
		ps->a[ps->top] = x;
		ps->top++;
	
}
int StackTop(Stack* ps)
{
	
	return  ps->a[ps->top - 1];
}
int StackSize(Stack* ps)
{
	return sizeof(int)*ps->top;
}
bool Stackempty(Stack* ps)
{
	if (ps->top == NULL)
	{
		return true;
	}
	else
	{
		return false;
	}
}

int main()
{
	Stack ps;
	StackInit(&ps);
	StackPush(&ps,2);
	StackPush(&ps,5);
	StackPush(&ps,8);
	StackPush(&ps,7);
	StackPush(&ps,10);
	StackPush(&ps,18);
	StackPush(&ps,1811);
	int size=StackSize(&ps);

	
	while(Stackempty(&ps)==false)
	{
	cout << StackTop(&ps) << endl;
	StackPop(&ps);
	}
	cout << size << endl;
}

各方法实现:

void StackInit(Stack*ps);

void StackPop(Stack* ps);
void StackPush(Stack* ps,int x);
int StackTop(Stack* ps);
int StackSize(Stack* ps);
bool Stackempty(Stack* ps)

1.StackInit初始化

void StackInit(Stack* ps)
{
	if (ps == NULL)
	{
		return;
	}
	ps->a = NULL;
	ps->capacity = 0;
	ps->top = 0;
}

2.void StackPop(Stack* ps)
 

void StackPop(Stack* ps)
{
	ps->top--;
	ps->a[ps->top] = NULL;
}

3.void StackPush(Stack* ps,int x);

void StackPush(Stack* ps,int x)
{
	if (ps == NULL)
	{
		return;
	}
	else if (ps->capacity == ps->top)
	{
		int newcapacity;
		if (ps->capacity == 0)
		{
			newcapacity = 4;
		}
		else
		{
			newcapacity = 2*ps->capacity;
		}
		ps->capacity = newcapacity;
		int* temp = new int[newcapacity];
		
		for (int i = ps->top;i > 0;i--)
		{
			temp[i - 1] = ps->a[i - 1];
		}
		
		
		ps->a = temp;
		
	}
		ps->a[ps->top] = x;
		ps->top++;
	
}

4.int StackTop(Stack* ps);

int StackTop(Stack* ps)
{
	
	return  ps->a[ps->top - 1];
}

5.int StackSize(Stack* ps);

int StackSize(Stack* ps)
{
	return sizeof(int)*ps->top;
}

6.bool Stackempty(Stack* ps)

bool Stackempty(Stack* ps)
{
	if (ps->top == NULL)
	{
		return true;
	}
	else
	{
		return false;
	}
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值