#include<iostream> //栈(C++)
#include <malloc.h>
using namespace std;
#define STACK_INIT_SIZE 100
#define STACKINCREMENT 10
//typedef struct BiTNode { //测试存放的指针类型
// int data;
// struct BiTNode* lchild, * rchild;
//}BiTNode, * BiTree;
//
//BiTree createb(BiTree T) { //创建含三个结点的二叉树
// T->data = 1;
// T->lchild = (BiTree)malloc(sizeof(BiTNode));
// T->rchild = (BiTree)malloc(sizeof(BiTNode));
// T->lchild->data = 2;
// T->rchild->data = 3;
// return T;
//}
typedef int ElemType;
typedef struct {
ElemType* base;
ElemType* top;
int stacksize;
}SqStack, * SqStacklist;
SqStacklist InitStack() { //创建空栈
SqStacklist S;
S = (SqStacklist)malloc(sizeof(SqStack));
S->base = (ElemType*)malloc(STACK_INIT_SIZE * sizeof(ElemType));
S->top = S->base;
S->stacksize = STACK_INIT_SIZE; //当前内存大小
return S;
}
ElemType pop(SqStacklist S) { //用e返回栈顶元素,并且删除栈顶元素
if (S->top == S->base) return 0;
ElemType e = *--S->top;
return e;
}
void PrintStack(SqStacklist S) { //输出栈中所有元素,并清空栈
SqStacklist S1;
S1 = new SqStack();
*S1 = *S; //将指针S里面的内容全部赋给S1
while (S1->top != S1->base) {
//二叉树栈中,pop(S)相当于指针,此处要改成pop(S1)->data
cout << pop(S1) << " "; //S已经是指针,不需要取地址了
}
}
void DeleteTop(SqStacklist S) { //删除栈顶元素(并不是真正删除,只是头指针向下移动一位)
S->top--;
}
void push(SqStacklist S, ElemType e) { //栈顶插入元素
if (S->top - S->base >= S->stacksize) {
S->base = (ElemType*)realloc(S->base, (S->stacksize + STACKINCREMENT) * sizeof(ElemType)); //重新为S->base分配内存
S->top = S->base + S->stacksize;
S->stacksize += STACKINCREMENT;
}
*S->top++ = e; //相当于*S->top=e; S->top++;
}
ElemType top(SqStacklist S) { //返回头部元素
ElemType e = *(S->top - 1);
return e;
}
int empty(SqStacklist S) { //判断栈是不是空的
if (S->top == S->base)
return 1;
else
return 0;
}
int S_size(SqStacklist S) { //返回栈的长度
SqStacklist S1;
S1 = new SqStack();
*S1 = *S;
int length = 0;
while (S1->top != S1->base) {
length++;
S1->top--;
}
return length;
}
int main() {
/*SqStacklist S;
S = InitStack();
BiTree T;
T = new BiTNode();
T = createb(T);
push(S, T);
push(S, T->lchild);
push(S, T->rchild);
PrintStack(S);
PrintStack(S);*/
int i, temp;
SqStacklist S;
S = InitStack();
int number;
cin >> number;
for (i = 0; i < number; i++) {
cin >> temp;
push(S, temp);
}
DeleteTop(S);
PrintStack(S);
return 0;
}
栈(C++)
于 2021-10-22 23:23:58 首次发布