數據結構-----順序棧的實現

#ifndef _SEQSTACK_H
#define _SEQSTACK_H

#include<iostream>
#include<assert.h>
using namespace std;

typedef int ElemType;

#define STACK_INIT_SIZE 8

typedef struct Stack
{
	ElemType *base;
	int       top;
	int       capacity;
}Stack;

void InitStack(Stack *st);        
bool IsFull(Stack *st);            
bool IsEmpty(Stack *st);
           
bool Push(Stack *st,ElemType x);       
bool Pop(Stack *st ); 
int length(Stack *st);            
bool GetTop(Stack *st,ElemType *x) ;
void ShowStack(Stack *st);                
void clear(Stack *st);            
void destory(Stack *st);          
 
#endif
#include"SeqStack.h"


bool IsFull(Stack *st)
{
	return st->top >= st->capacity;
}

bool IsEmpty(Stack *st)
{
	return st->top == 0;
}

void InitStack(Stack *st)
{
	st->base = (ElemType *)malloc(sizeof(ElemType)*STACK_INIT_SIZE);
	assert(st->base != NULL);
	st->capacity = STACK_INIT_SIZE;
	st->top = 0;
}

bool Push(Stack *st, ElemType x)
{
	if(IsFull(st))
	{
		cout<<"棧已滿,"<<x<<"不能入棧!"<<endl;
		return false;
	}
	st->base[st->top++] = x;
	return true;
}

bool Pop(Stack *st)
{
	if(IsEmpty(st))
	{
		cout<<"棧已空,不能出棧!"<<endl;
		return false;
	}

	st->top--;
	return true;
}
 
bool GetTop(Stack *st,ElemType *x)  
{  
    if(IsEmpty(st))  
    {  
        cout<<"棧爲空:"<<endl;  
        return false;  
    }  
    *x = st->base[--st->top]; 
	cout<<"棧頂是:"<<*x<<endl;
    return true;  
}  

void clear(Stack *st)
{
	st->top = 0;
}
void destory(Stack *st)
{
	free(st->base);
	st->base = NULL;
	st->top = 0;
	st->capacity = 0;
}

void ShowStack(Stack *st)
{
	for(int i=st->top-1; i>=0; --i)
	{
		cout<<st->base[i]<<endl;
	}
}
  
int length(Stack *st)  
{  
	cout<<st->top<<endl;
    return st->top;  
}  

#include"SeqStack.h"

void main()
{
	Stack st;
	InitStack(&st);
	int select = 1; 
	ElemType item;
	while(select)
	{
		cout<<"**********SeqStack*******************"<<endl;
		cout<<"******     hello!menu     ***********"<<endl;
		cout<<"* [0] quit_system     [1] push      *"<<endl;
		cout<<"* [2] pop             [3] Show_Stack*"<<endl; 
		cout<<"* [4] length          [5] gettop    *"<<endl;
		cout<<"* [6] clear           [7] destory   *"<<endl; 
		cout<<"* [8] InitStack                     *"<<endl; 
		cout<<"******************  over   **********"<<endl;
		cout<<"請選擇:>";
		cin>>select;
		switch(select)
		{
		case 1:
			cout<<" 請輸入要入棧的值(-1結束):>";
			while(cin>>item,item!=-1)
			{
				Push(&st,item);
			}
			break;
		case 2:
				Pop(&st);
			break;
		case 3:
			ShowStack(&st);
			break;
		case 4:
			length(&st);
			break;
		case 5:
			GetTop(&st,&item  );
			  
			break;
		case 6:
			clear(&st);
			break;
		case 7:
				destory(&st);
				break;
		case 8:
				InitStack(&st);
				break;
		default:
			break;
		}
	}

}

       

   









發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章