zoukankan      html  css  js  c++  java
  • 栈的链表实现

    栈ADT链表实现的类型声明

    #ifndef _Stack_h
    struct Node;
    typedef struct Node *PtrToNode;
    typedef PtrToNode Stack;
    
    int IsEmpty( Stack S);
    Stack CreateStack ( void );
    void DisposeStact ( Stack S );
    void MakeEmpty ( Stack S );
    void Push ( ElementType X, Stack S);
    ElementType Top ( Stack S );
    void Pop ( Stack S);
    
    #endif /* _Stack_h */
    
    struct Node
    {
    	ElementType Element;
    	PtrToNode Next;
    };
    

    测试栈是否是空栈

    int IsEmpty( Stack S )
    {
    	return S->Next == NULL;
    }
    

    创建一个空栈

    Stack CreateStack( void )
    {
    	Stack S;
    	S = malloc( sizeof( struct Node ));
    	if( S == NULL )
    		FatalError("Out of space!!!");
    	S->Next == NULL;
    	MakeEmpty( S );
    	return S;
    }
    void MakeEmpty( Stack S )
    {
    	if( S == NULL )
    		Error("Must use CreateStack first");
    	else
    		while( !IsEmpty(S))
    			Pop( S );
    }
    

    Push进栈

    void Push ( ElementType X,Stack S)
    {
    	PtrToNode TmpCell;
    	TmpCell = malloc( sizeof( struct Node));
    	if(TmpCell == NULL)
    		FataError( "Out of space" );
    	else
    	{
    		TmpCell->Element = x;
    		Tmpcell->Next = S->Next;
    		S->Next = TmpCell;
    	}
    }
    

    返回栈顶元素

    ElementType Top( Stack S )
    {
    	if( !IsEmpty(S) )
    		return S->Next->Element;
    	Error("Empty stack" );
    	return 0;
    }
    

    Pop栈

    void Pop( Stack S )
    {
    	PtrToNode FirstCell;
    	if(IsEmpty(S))
    		Error("Empty stack");
    	else
    	{
    		FirstCell = S->Next;
    		S->Next = S->Next->Next;
    		free(FirstCell);
    	}
    }
  • 相关阅读:
    10A:子串计算
    09I:鸡蛋的硬度
    09H:数字组合
    09G:登山
    09F:股票买卖
    09E-计算字符串距离
    09D-最大上升子序列和
    09C-全排列
    02C-垃圾炸弹
    【c#基础】vs2019设置高级选项
  • 原文地址:https://www.cnblogs.com/y3w3l/p/6351417.html
Copyright © 2011-2022 走看看