• MOOC 2.2 堆栈


    1. 顺序存储

    #include <cstdio>
    #define MaxSize <存储元素的最大个数> 
    typedef struct SNode *Stack;
    struct SNode
    {
    	ElementType Data[MaxSize];
    	int Top;
    };
    
    // 1. 入栈
    void Push(Stack PtrS, ElementType item)
    {
    	if(PtrS->Top == MaxSize - 1)
    	{
    		printf("堆栈满");
    		return ;
    	}
    	else
    	{
    		PtrS->Data[++(PtrS->Top)] = item;
    		return ;
    	}
    } 
    
    // 2. 出栈
    ElementType Pop(Stack PtrS)
    {
    	if(PtrS->Top == -1)
    	{
    		printf("堆栈空");
    		return ERROR; 
    	}
    	else
    	{
    		return (PtrS->Data[(PtrS->Top)--]);
    	}
    } 
    

      

    共享栈

    // 共享栈
    #define MaxSize <存储元素的最大个数>
    struct DStack
    {
    	ElementType Data[MaxSize];
    	int Top1;
    	int Top2;
    }S;
    
    S.Top1 = -1;
    S.Top2 = MaxSize;
    
    void Push(struct DStack *PtrS, ElementType item, int Tag)
    {
    	if(PtrS->Top1 + 1 == PtrS->Top2)
    	{
    		printf("堆栈满");
    		return ; 
    	}
    	if(Tag == 1)
    		PtrS->Data[++(PtrS->Top1)] = item;
    	else
    		PtrS->Data[--(PtrS->Top2)] = item;
    	return ;
    }
    
    ElementType Pop(struct DStack *PtrS, int Tag)
    {
    	// Tag作为区分两个堆栈的标志, 取值为1和2 
    	if(Tag == 1)
    	{
    		if(PtrS->Top1 == -1)
    		{
    			printf("堆栈1空");
    			return NULL; 
    		}
    		else
    		{
    			return PtrS->Data[(PtrS->Top1)--];
    		}
    	}
    	else
    	{
    		if(PtrS->Top2 == MaxSize)
    		{
    			printf("堆栈2空");
    			return NULL; 
    		}
    		else
    		{
    			return PtrS->Data[(PtrS->Top2)++];
    		}
    	}
    }
    

      

    3. 链式栈

    // 堆栈的链式存储
    typedef struct SNode *Stack;
    struct SNode
    {
    	ElementType Data;
    	struct SNode *Next;
    };
    // 栈顶指针top应该在链表的头部
    
    // 1. 初始化堆栈(建立空栈) 
    Stack CreateStack()
    {
    	Stack S;
    	S = (Stack)malloc(sizeof(struct SNode));
    	S->Next = NULL;
    	return S;
    } 
    
    // 判断堆栈是否为空
    int IsEmpty(Stack S)
    {
    	return (S->Next == NULL);
    }
    
    // 插入结点
    void Push(ElementType item, Stack S)
    {
    	struct SNode *TmpCell;
    	TmpCell = (struct SNode *)malloc(sizeof(struct SNode));
    	TmpCell->Data = item;
    	TmpCell->Next = S->Next;
    	S->Next = TmpCell;
    } 
    
    // 删除结点
    ElementType Pop(Stack S)
    {
    	struct SNode *FirstCell;
    	ElementType TopElem;
    	if(IsEmpty(S))
    	{
    		printf("堆栈空");
    		return NULL; 
    	}
    	else
    	{
    		FirstCell = S->Next;
    		S->Next = FirstCell->Next;
    		TopElem = FirstCell->Data;
    		free(FirstCell);
    		return TopElem;
    	}
    } 
    

      

  • 相关阅读:
    014_v2 python基础语法_dict
    6-05使用SQL语句删除数据
    6-04使用SQL语句更新数据
    6-03使用SQL语句一次型向表中插入多行数据
    6-02使用SQL语句向表中插入数据
    6-01T-SQL中的运算符
    5-08删除表
    5-07删除约束
    使用SQL语句向已有数据表添加约束
    5-06使用Sql 语句为表添加约束
  • 原文地址:https://www.cnblogs.com/mjn1/p/11441604.html
Copyright © 2020-2023  润新知