数据结构——栈的数组实现

       栈是一种先入后出的数据结构,在计算机表达式求值时是一种常用的数据结构。具体提出:在解决需要判断将来问题才来作出判断时,常需要将当前的数据保存,而栈就是一种这样的数据结构,需要保存当前数据时,先压入堆栈,使用时再弹出。堆栈也可以认为是具有一定约束的线性表,其插入与删除都作用在同一个位置(栈顶)。

一、对于栈的定义:

1、栈存储的数据类型;

2、栈顶;

3、栈的最大容量;

C语言实现:

struct SNode{
    ElementType *Data;        /* 堆栈数据 */
    Position Top;            /* 栈顶指针 */
    int MAXSIZE;            /* 栈的最大容量 */  
};

二、创建空栈

创建一个空栈,首先要给定栈的大小,然后对栈顶初始化。

Stack Create_Stack(int MaxSize)
{
    Stack S = (Stack)malloc(sizeof(struct SNode));
    S->Data = (ElementType *)malloc(MaxSize * sizeof(ElementType));
    S->Top = -1;        /* Top =-1 空栈 */
    S->MAXSIZE = MaxSize; 
}

三、压栈

压栈实际上就是在栈顶插入数据,栈顶同时加1。在压栈之前还需要判断是否栈满。

Bool Push(Stack S, ElementType X)
{
    if( ISFull(S) ){
        printf("栈满\n");
        return false;
    }
    else{
        S->Data[++(S->Top)]    = X;
        return true;
    }    

四、出栈

出栈实际上就是删除栈顶数据,栈顶同时减1。在出栈之前还需要判断栈空。

ElementType Pop(Stack S)
{
    if( ISEmpty(S) ){
        printf("栈空\n");
        exit(false);
    }
    else{
        return S->Data[(S->Top)--];
    }    
}  

总结:其实栈也是一种特殊的线性表,多用用就熟悉了。下面给出一个实例:

#include <stdio.h>
#include <stdlib.h>

#define false 0
#define true 1 

typedef int ElementType;
typedef int Position;
typedef int Bool;

typedef struct SNode *Stack;
struct SNode{
	ElementType *Data;		/* 堆栈数据 */
	Position Top;			/* 栈顶指针 */
	int MAXSIZE;			/* 栈的最大容量 */  
};

Stack Create_Stack(int MaxSize);
Bool ISEmpty(Stack S);
Bool ISFull(Stack S);
Bool Push(Stack S, ElementType X);
ElementType Pop(Stack S);

int main()
{
	Stack S;
	int MaxSize;
	int i;
	scanf("%d",&MaxSize);
	S = Create_Stack(MaxSize);
	
	for( i = 1; !ISFull(S) ; i++)
		Push(S,i);
	for( ;!ISEmpty(S); ) 
		printf("%d\n",Pop(S));
	return 0;
} 

/*
**	创建空栈
*/ 
Stack Create_Stack(int MaxSize)
{
	Stack S = (Stack)malloc(sizeof(struct SNode));
	S->Data = (ElementType *)malloc(MaxSize * sizeof(ElementType));
	S->Top = -1;		/* Top =-1 空栈 */
	S->MAXSIZE = MaxSize; 
}

/*
**	判断空栈 
*/
Bool ISEmpty(Stack S)
{
	return S->Top == -1 ;
} 

/* 
**	判断栈满
*/
Bool ISFull(Stack S)
{
	return S->Top == S->MAXSIZE - 1;
} 

/*
**	压栈 
*/
Bool Push(Stack S, ElementType X)
{
	if( ISFull(S) ){
		printf("栈满\n");
		return false;
	}
	else{
		S->Data[++(S->Top)]	= X;
		return true;
	}	
} 

/*
**	出栈
*/
ElementType Pop(Stack S)
{
	if( ISEmpty(S) ){
		printf("栈空\n");
		exit(false);
	}
	else{
		return S->Data[(S->Top)--];
	}	
}  

猜你喜欢

转载自blog.csdn.net/Bridge3/article/details/82561260
今日推荐