#include <iostream>
#include <cstdlib>
#include <string>
#define StackInitSize 5
#define StackIncreace 2
using namespace std;
bool em(struct Stack *);
struct Stack{
int Stack_size; //目前栈的容量
int Stack_num;
//定义两个指针,top指向栈顶,base指向栈底
int *top;
int *base;
};
void InitStack(struct Stack *stack){
stack->base = new int[StackInitSize];
if(stack->base == nullptr){
cout << "memory allocation false!" << endl;
exit(-1);
}else{
stack->top = stack->base;
stack->Stack_size = StackInitSize;
stack->Stack_num = 0;
return;
}
}
bool push(struct Stack *stack, int val){
*stack->top = val;
(stack->top)++;
return true;
}
bool Stack_Add(struct Stack *stack, struct Stack *temp, int val){
temp->base = new int[stack->Stack_size + StackIncreace];
if (temp->base == nullptr){
cout << "memory allocation false!" << endl;
return false;
}else{
temp->top = temp->base;
stack->Stack_size += StackIncreace;
for (int i =0; i < stack->Stack_num - 1; i++){
temp->base[i] = stack->base[i];
++(temp->top);
}
*temp->top = val;
(temp->top)++;
delete [] stack->base;
stack->base = temp->base;
stack->top = temp->top;
return true;
}
}
void Pop(struct Stack *stack,int &val){
if (em(stack)){
cout << "stack is empty" << endl;
}else{
val = *stack->top;
}
return;
}
bool em(struct Stack *stack){
if (stack->base == stack->top){
return true;
}else{
return false;
}
}
void ShowStack(struct Stack *stack){
for (int i = 0; i != stack->Stack_num; i++){
cout << stack->base[i] << ",";
}
cout << endl;
return;
}
int main(){
int val,option;
Stack stack;
InitStack(&stack);
Stack temp;
cout << "Please,input a num for stack(use whitesapce separated): " << endl;
while(cin.peek() != '\n'){
cin >> val;
++stack.Stack_num;
if (stack.Stack_num <= stack.Stack_size){
push(&stack,val);
}else{
Stack_Add(&stack, &temp, val);
}
}
system("pause");
return 0;
}
c++实现顺序栈
最新推荐文章于 2022-10-09 09:32:02 发布
该博客主要展示了如何使用C++实现一个动态栈,包括初始化、压栈、扩容、添加元素、弹栈和检查栈空等功能。代码中定义了结构体Stack,并提供了相应的操作函数,如Stack_Init、push、Stack_Add等,用于处理栈的操作。在栈满时,通过Stack_Add函数动态扩容栈的容量。在main函数中,展示了如何向栈中输入数值并进行操作。
摘要由CSDN通过智能技术生成