顺序栈

来源:互联网 发布:西南科技大学网络教学 编辑:程序博客网 时间:2024/06/14 07:51
#include<iostream>
using namespace std;
#define Elemtype unsigned int
#define INIT_SIZE 10
#define INCREMENT 10
typedef struct
{
Elemtype* base;
Elemtype* top;
unsigned int stacklength;
int stacksize;
}stack;
bool stack_init(stack& my_stack)
{
my_stack.base=(Elemtype*)malloc(sizeof(Elemtype)*INIT_SIZE);
if (my_stack.base == NULL)
return false;
else
{
my_stack.top = my_stack.base;
my_stack.stacklength = 0;
my_stack.stacksize = INIT_SIZE;
return true;
}
}
int push(stack& my_stack,Elemtype num)
{
if (my_stack.stacklength < my_stack.stacksize)
{
*my_stack.top++ = num;
my_stack.stacklength++;
}
else
{
my_stack.base=(Elemtype*)realloc(my_stack.base, sizeof(Elemtype)*(my_stack.stacksize + INCREMENT));
if (my_stack.base == NULL)
exit(OVERFLOW);
my_stack.stacksize = my_stack.stacksize + INCREMENT;
*my_stack.top++ = num;
my_stack.stacklength++;
return true;
}
}
int pop(stack& my_stack,Elemtype& pop_result)
{
if (my_stack.top == my_stack.base)
exit(OVERFLOW);
else
pop_result = *--my_stack.top;//栈顶指针是指向栈顶元素的上一个位置
my_stack.stacklength--;
}
bool get_top(stack& my_stack, Elemtype& top)
{
if (my_stack.stacklength == 0)
return false;
else
{
top = *(my_stack.top - 1);//减1是向下移动一个Elemtype类型所对应的数据类型的内存大小
return true;
}
}
int* p;
int main()
{
cout << p;//00000000
stack my_stack;
stack_init(my_stack);
unsigned int temp;
unsigned int nums;
Elemtype top;
cout << "nums" << endl;
cin >> nums;
cout << "input nums to be stored" << endl;
for (int i = 0; i < nums; i++)
{
cin >> temp;
push(my_stack, temp);
}
pop(my_stack,temp);
get_top(my_stack, top);
cout << "top=" << top;
return 0;
}
原创粉丝点击