首页 > 代码库 > 栈的基本操作

栈的基本操作

栈的存储结构有两种:一种是线性栈,一种是链式栈。下面分别是这两种存储结构的实现。

线性栈:

#define STACK_INIT_SIZE 10
#define STACK_REALLOCATION 2

typedef int ElemType;

typedef struct SqStack
{
	ElemType *base;
	int top;
	int stacklength;
}SqStack;

void InitSqStack(SqStack *S)
{
	S->base = (ElemType*)malloc(STACK_INIT_SIZE*sizeof(ElemType));
	if (!S->base)
		exit(1);
	S->top = 0;
	S->stacklength = STACK_INIT_SIZE;
}

void Push_SqStack(SqStack *S,ElemType e)
{
	if (S->top == S->stacklength){
		S->base = (ElemType*)realloc(S->base,(S->stacklength

+STACK_REALLOCATION)*sizeof(ElemType));
		if (!S->base)
			exit(1);
		S->stacklength += STACK_REALLOCATION;
	}
	S->base[S->top] = e;
	++S->top;
}

int Pop_SqStack(SqStack *S, ElemType *e)
{
	if (S->top == 0)
		return 0;
	--S->top;
	*e = S->base[S->top];
	return 1;
}

int GetTopElem_SqStack(SqStack *S, ElemType *e)
{
	if (S->top == 0)
		return 0;
	*e = S->base[S->top-1];
	return 1;
}

int isSqStackEmpty(SqStack S)
{
	if (S.top == 0)
		return 1;
	else
		return 0;
}

void SqStack_test()
{
	SqStack S;
	InitSqStack(&S);
	ElemType e;
	printf("Please input some numbers(Ctrl + Z to end).\n");
	while (scanf("%d", &e) != EOF)
		Push_SqStack(&S,e);
	printf("The out stack sequence is:\n");
	while (!isSqStackEmpty(S)){
		Pop_SqStack(&S,&e);
		printf("%d ",e);
	}
	printf("\n");
}

int main()
{
	SqStack_test();
	return 0;
}




链式栈:


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

#define STACK_INIT_SIZE 10
#define STACK_REALLOCATION 2

typedef int ElemType;

typedef struct LinkStack
{
	ElemType data;
	struct LinkStack *next;
}StackNode,*StackPNode;

StackPNode InitLinkStack()
{
	StackPNode head = (StackPNode)malloc(sizeof(StackNode));
	if (!head)
		exit(1);
	head->next = NULL;
	head->data = http://www.mamicode.com/0;>