Catalog
栈的实现
#include<iostream>
using namespace std;
#define STACK_INIT_SIZE 100
#define STACKINCREASEMENT 10
#define OK 1
typedef int SElemType;
typedef struct {
SElemType* base;
SElemType* top;
int stacksize;
}SqStack;
SqStack InitStack(SqStack &S) {
S.base = (SElemType*)malloc(sizeof(SElemType)* STACK_INIT_SIZE);
S.top = S.base ;
S.stacksize = STACK_INIT_SIZE;
return S;
}

SElemType GetTop(SqStack S, SElemType& e) {
if (S.top == S.base) return false;
e = *(S.top - 1);
return e;
}

bool Push(SqStack& S, SElemType e) {
if (S.top - S.base >= S.stacksize) {
S.base = (SElemType*)realloc(S.base, (S.stacksize + STACKINCREASEMENT) * sizeof(SElemType));
S.top = S.base + S.stacksize;
S.stacksize += STACKINCREASEMENT;
}
*S.top++ = e;
return 1;
}
SElemType Pop(SqStack& S, SElemType& e) {
if (S.top == S.base) return 0;
e = *--S.top;
return e;
}

void print(SqStack S) {
while (S.top != S.base) {
cout << *--S.top <<" ";
}
cout << endl;
}
int main() {
printf("栈的元素个数:");
int n;
cin >> n;
SqStack S;
InitStack(S);
for (int i = 0; i < n; i++) {
int temp;
cin >> temp;
Push(S, temp);
}
printf("栈顶的值为:");
int k;
printf("%d\n", GetTop(S, k));
print(S);
int del;
int t = Pop(S, del);
if (t) printf("删除栈顶值%d成功\n",t);
printf("剩余的值为:");
print(S);
printf("继续插入一个值:");
int extra;
cin >> extra;
Push(S,extra);
cout << endl;
print(S);
return 0;

}
Author: superzhaoyang
Link: http://yoursite.com/2019/09/21/栈的实现/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.
Donate
  • 微信
  • 支付宝

Comment