zoukankan      html  css  js  c++  java
  • 栈的数组实现

    栈的声明

    #ifndef _Stack_h
    struct StackRecord;
    typedef struct StackRecord *Stack;
    
    int IsEmpty ( Stack S);
    int IsFull ( Stack S);
    Stack CreateStack ( int MaxElements );
    void DisposeStack ( Stack S );
    void MakeEmpty ( Stack S);
    void Push (ElementType X,Stack S);
    ElementType TopAndPop ( Stack S);
    
    #endif 
    
    #define EmptyTOS (-1)
    #define MinStackSize (5)
    
    struct StackRecord
    {
    	int Capacity;
    	int TopOfStack;
    	ElementType *Array;
    }
    

    创建一个空栈

    Stack CreateStack( int MaxElements )
    {
    	Stack S;
    	if( MaxElements < MinStackSize )
    		Error("Stack size is too small");
    	S = malloc( sizeof(struct StackRecord));
    	if( S = NULL )
    		FatalError("Out of space!!!");
    	S->Array = malloc( sizeof(ElementType)*MaxElements);
    	if( S->Array == NULL)
    		FatalError( "Out of space!!!");
    	S->Capacity = MaxElements;
    	MakeEmpty( S );
    	
    	return S;
    }
    

    释放栈

    void DisposeStack( Stack S)
    {
    	if( S != NULL)
    	{
    		free( S->Array );
    		free( S );
    	}
    }
    

    检测一个栈是否为空

    int IsEmpty( Stack S )
    {
    	return S->TopOfStack == EmptyTOS;
    }
    

    创建一个空栈

    void MakeEmpty( Stack S )
    {
    	 S->TopOfStack == EmptyTOS;
    }
    

    Push进栈

    void Push( ElementType X,Stack S )
    {
    	if( IsFull(S))
    		Error("Full stack");
    	else
    		S->Array[ ++S->TopOfArray ] = X;
    }
    

    将栈顶返回

    ElementType Top( Stack S )
    {
    	if (!IsEmpty(S))
    		return S->Array[ S->TopOfStack ];
    	Error("Empty stack");
    	return 0;
    }
    

    从栈弹出元素

    void Pop( Stack S)
    {
    	if( IsEmpty(S))
    		Error("Empty stack");
    	else
    		S->TopOfStack--;
    }
  • 相关阅读:
    [洛谷][P1503][鬼子进村][Treap]
    [noi 2004] 郁闷的出纳员
    bzoj 3224,tyvj 1728普通平衡树
    Treap
    [模拟赛]棘手的操作
    bzoj 4551[Tjoi2016&Heoi2016]树
    bzoj2527 [Poi2011]Meteors
    bzoj4152 [AMPPZ2014]The Captain
    bzoj4516 [Sdoi2016]生成魔咒
    bzoj4547 小奇的集合
  • 原文地址:https://www.cnblogs.com/y3w3l/p/6351757.html
Copyright © 2011-2022 走看看