栈的属性为先进后出,后进先出;故只能通过栈顶删除和插入;
实现方法如下:
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;
}
}