동적 스택의 구현(CPP)

1401 단어
#include<iostream>
#define INCREMENTSIZE 10 
#define INITIALSIZE 20
using namespace std;


typedef struct{
	int *data;
	int top,stackSize;	
}SqStack;



bool initStack(SqStack & S){
	int *a=(int *)malloc(INITIALSIZE * sizeof(int));
	S.data=a;
	S.top=-1;
	S.stackSize=INITIALSIZE;
	return true;	
}
bool isFull(SqStack &S){
	if(S.top == S.stackSize-1) return true;
	else return false;	
}

bool increStack(SqStack &S){
	int *a=(int *)malloc(S.stackSize* sizeof(int));
	a=S.data;
	int *b=(int *)malloc((S.stackSize+INCREMENTSIZE)* sizeof(int));
	for(int i=0;i<=S.top;i++)
	  b[i]=a[i];
    S.data=b;
    S.stackSize+= INCREMENTSIZE;
    free(a); 

	return false;
	
}

bool push(SqStack &S,int x){
	if(isFull(S)) increStack(S);
	S.data[++ S.top]=x;
	return true;	
}

bool pop(SqStack &S,int &x){
	if(S.top==-1) return false;
	x=S.data[S.top --];	
	return true;	
}

bool getTop(SqStack S,int &x){
	if(S.top== -1) return false;
	x=S.data[S.top];
	return true;	
}

bool isEmpty(SqStack S){
	if(S.top == -1) return true;
	else return false;	
}
bool free(SqStack &S){
	S.top=-1;
	S.stackSize= 0;
	free(S.data);
	return true;	
}
int main(){
	int x,i;
	SqStack S;
	initStack(S);
	for(i=0;i<40;i++)
       push(S,i);
    while(! isEmpty(S)){
    	pop(S,x);
    	cout<<x<<"  ";    	
    }
    
    cout<<endl;
	free(S);
}

좋은 웹페이지 즐겨찾기