• 数据结构之---C语言实现共享栈


    所谓共享栈是两个栈在一个顺序的存储空间中。两个栈的栈底各自是存储空间的首尾地址。

    如图我们能够将两个栈构造成一个:

    如图:


    从这里也就能够分析出来,栈1为空时,就是top1等于-1时。而当top2等于n时,即是栈2为空时,那么什么时候栈满呢?

         想想极端的情况,若栈2是空栈,栈1的top1等于n-1时,就是栈1满了。反之,当栈1为空栈时。top2等于0时,为栈2满。

    但很多其它的情况,事实上就是刚才说的,两个栈见面之时,也就是两个指针之间相差1时。即top1+1==top2为栈满

    详细的实现代码例如以下:


    //共享栈
    //杨鑫
    #include <stdio.h>
    #include <stdlib.h>
    #define MaxSize 60 
    #define OK      1      
    #define ERROR   0      
    #define TRUE    1      
    #define FALSE   0    
    typedef int ElemType;  
    typedef int Status;  
    typedef struct {  
        ElemType    data[MaxSize];  
        int         top1;                    
        int         top2;					
    }Stack,  *pStack;  
    
    Status init_Stack(pStack S)
    {
    	S->top1 = -1;
    	S->top2 = MaxSize;
    	return OK; 
    }
    
    Status push_Stack(pStack S, ElemType e, int stackNumber)
    {
    	if (S->top1+1 == S->top2)
    		return ERROR;
    	switch(stackNumber)
    	{
    		case 1:		
    				S->data[++S->top1] = e;		
    				break;
    		case 2:		
    				S->data[--S->top2] = e;		
    				break;
    	}
    	return OK;
    }
    
    
    Status pop_Stack(pStack S, ElemType *e, int stackNumber)
    {
    	if (1 == stackNumber)
    	{	
    		if (-1 == S->top1)		
    			return ERROR;
    		*e = S->data[S->top1--];
    	}
    	else if (2 == stackNumber)
    	{
    		if (MaxSize == S->top2)
    			return ERROR;
    		*e = S->data[S->top2++];
    	}
    	return OK;
    }
    
    
    Status dis_pStack(pStack S, int stackNumber)
    {
    	int i;
    	if (1 == stackNumber)
    	{
    		if (-1 == S->top1)
    			return ERROR;
    
    		printf("栈1中的元素为:
    ");
    		for (i=0; i<=S->top1; ++i)
    			printf("%d ", S->data[i]);
    		printf("
    ==================================
    ");
    	}
    	else if (2 == stackNumber)
    	{
    		if (MaxSize == S->top2)
    			return ERROR;
    		printf("栈2中的元素为:
    ");
    		for (i=MaxSize-1; i>=S->top2; --i)	
    			printf("%d ", S->data[i]);
    		printf("
    ==================================
    ");
    	}
    }
    
    int main()
    {
    	printf("======共享栈===========
    
    ");
    	Stack S;
    	ElemType e;
    	init_Stack(&S);
    	push_Stack(&S, 1, 1);
    	push_Stack(&S, 2, 1);
    	push_Stack(&S, 3, 1);
    	push_Stack(&S, 4, 1);
    	push_Stack(&S, 5, 1);
    	push_Stack(&S, 6, 1);
    	pop_Stack(&S, &e, 1);
    	push_Stack(&S, 10, 2);
    	push_Stack(&S, 9, 2);
    	push_Stack(&S, 8, 2);
    	push_Stack(&S, 7, 2);
    	dis_pStack(&S, 1);
    	dis_pStack(&S, 2);
    	return 0;
    }
    
    
    
    

    图片:


  • 相关阅读:
    java基础知识复习
    红黑二叉查找树(原理、实现)
    Django admin
    redis+sentinel 安装与配置
    浅谈saltstack
    python3 通过smtplib模块发送邮件
    django 自定义分页模块
    chouti项目
    Django 进阶篇二
    Django 进阶篇
  • 原文地址:https://www.cnblogs.com/yutingliuyl/p/6882619.html
Copyright © 2020-2023  润新知