码迷,mamicode.com
首页 > 其他好文 > 详细

栈的链表实现

时间:2014-12-07 17:39:05      阅读:154      评论:0      收藏:0      [点我收藏+]

标签:blog   io   ar   os   sp   div   log   ef   as   

/* 
MyArryLinkstack.h 
*/
#ifndef _MYARRYLINKSTACK_H_
#define _MYARRYLINKSTACK_H_
#include <stdlib.h>
#define ElementType int
#define EmptyTOS (-1)
#define MinStackSize (5)
typedef struct {
	int Capacity;
	int Top;
	ElementType *Array;
}StackRecord, *pStack;
int IsEmpty(pStack S);
int IsFull(pStack S);
pStack CreatStack(int MaxElements);
void DisposeStack(pStack S);
void MakeEmpty(pStack S);
ElementType GetTop(pStack S);
void Push(pStack S, ElementType x);
void Pop(pStack S);
ElementType TopAndPop(pStack S);
#endif

/*
MyArryLinkstack.c
*/
#include "MyArryLinkstack.h"
/*栈的创建,数组实现*/
pStack CreatStack(int MaxElements)
{
	pStack S;
	if (MaxElements < MinStackSize)
		perror(" Stack is too small!");

	S =(pStack) malloc(sizeof(StackRecord));
	if (S == NULL)
		perror("Out of Space!");
	
	S->Array = malloc(sizeof(ElementType) * MaxElements);
	if (S->Array == NULL)
		perror("Out of Space!!!");
	S->Capacity = MaxElements;
	MakeEmpty(S);

	return S;
}
/*创建一个空栈*/
void MakeEmpty(pStack S)
{
	S->Top = EmptyTOS; 
}

/*判断是否空栈*/
int IsEmpty(pStack S)
{
	return S->Top == EmptyTOS;
}

/*判断是否满栈*/
int IsFull(pStack S)
{
	return S->Top == S -> Capacity - 1;
}

/*进栈*/
void Push(pStack S, ElementType x)
{
	if (IsFull(S))
		perror("Full Stack!");
	else
		S->Array[++S->Top] = x;
}
/*出栈*/
void Pop(pStack S)
{
	if (IsEmpty(S))
		perror("Empty Stack!");
	else
		S->Top--;
}
/*取得栈顶元素*/
ElementType GetTop(pStack S)
{
	if (IsEmpty(S)){
		perror("Empty Stack!");
		return 0;
	}
	else
		return S->Array[S->Top];
}

/*
main.c
*/
/* LinkStackTest.c */
#include <stdio.h>
#include "MyArryLinkstack.h"

int main()
{
	pStack pS = NULL;
	int a;
	pS = CreatStack(5);
	Push(pS, 1);
	a = GetTop(pS);
	Push(pS, 3);
	a = GetTop(pS);
	Push(pS, 5);
	a = GetTop(pS);
	Push(pS, 7);
	a = GetTop(pS);
	Push(pS, 9);
	a = GetTop(pS);
	Pop(pS);
	a = GetTop(pS);
}

  

栈的链表实现

标签:blog   io   ar   os   sp   div   log   ef   as   

原文地址:http://www.cnblogs.com/mrethan/p/4149542.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!