堆栈(简单应用 · 数据结构)

这里是一个简单的堆栈的应用。

#include<stdio.h>
#include<malloc.h>
#define MAXSIZE 100

typedef struct SNode *PtrToSNode;
typedef int Position;
struct SNode
{
	int *date;
	int Top;
	int MaxSize;
};
typedef PtrToSNode Stack;

void show();
Stack CreatStack(int MaxSize);
bool isfull(Stack S);
bool Push(Stack S, int X );
bool isempty(Stack S);
int Pop(Stack S);
void Transfer(Stack S, int date );

int main()
{
	int i, date=0, n=0;
	Stack S = (Stack)malloc(sizeof(struct SNode));
	
	while(1)
	{
	    show();
	    scanf("%d", &n);
	    if( n==0 )
	    break;
	    
        switch(n)
        {
       	case 1:
        {
       	S = CreatStack(MAXSIZE);
        i = 0;
        printf("输入数字,输入0时退出:");	
        while(1)
	        {
	        scanf("%d", &date);
	        if(date == 0 || i>MAXSIZE)
	        break;
	        Push(S, date);
	        i++;
	        }
        }
        break;
       
        case 2:
        printf("出栈数字为:%d\n\n", Pop(S));
        break;
       
        case 3:
        {
        printf("当前堆栈顺序为:");
		while(true)
	        {
	        	printf("%d", Pop(S));
	        	if( S->Top == -1 )
	        	break;
	        }
	        printf("\n\n");
        }
        break;
       
        case 4:
        {
	   	printf("请输入一个十进制的正整数:");
		scanf("%d" , &date);
		S = CreatStack(MAXSIZE); 
	    Transfer(S, date);
        }
        break;
        }
    }
}
Stack CreatStack(int MaxSize)
{
	Stack S = (Stack)malloc(sizeof(struct SNode));
	S->date = ( int * )malloc(MaxSize*sizeof(int));
	S->Top = -1;
	S->MaxSize = MaxSize;
	
	return S;
}

bool isfull(Stack S)//查看是否栈满 
{
	return ( S->Top == S->MaxSize-1 );
}
bool Push( Stack S, int X )//入栈操作 
{
	if(isfull(S))
	{
	printf("堆栈满");
	return false;
	}
	else
	{
	S->date[++(S->Top)] = X;
	return true;
    }
}

bool isempty(Stack S)
{
	return (S->Top==-1);
}

int Pop(Stack S)//出栈操作 
{
	if(isempty(S))
	{
		printf("堆栈空");
	    return false;	
	}
	else
	{
		return (S->date[(S->Top)--]);
	}
}

void Transfer(Stack S, int date )
{
	Position u=date, k=0;
	while(u)
	{   
		k = u%2;
		u = u/2;
		Push(S, k);
	}
	while(1)
    {
    	printf("%d", Pop(S));
    	if( S->Top==-1 )
    	break;
    }
}

void show() //显示堆栈菜单 
{
	printf("\n\n");
	printf("                        堆栈显示系统            \n"); 
	printf("               *******************************\n");
	printf("               *        1-----进 栈          *\n"); 
	printf("               *        2-----出 栈          *\n");
	printf("               *        3-----显 示          *\n");
	printf("               *        4-----数 字 转 换    *\n");
	printf("               *        0-----返 回          *\n");
	printf("               *******************************\n");
	printf("\n");
	printf("请选择菜单序号输入:"); 
}



编译器:DEV C++






阅读更多
上一篇约瑟夫环(队列*堆栈)
下一篇二叉搜索树(递归遍历 · 数据结构)
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭
关闭