关闭

栈的C语言 数组实现

标签: C数组实现
195人阅读 评论(0) 收藏 举报
分类:

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

#define EmpytTos -1
#define MinStackSize 5


struct StackRecord
{
	int Capacity;
	int TopOfStack;
	ElementType *Array;
};

//typedef struct StackRecord * Stack;

Stack
CreateStack(int MaxStackSize)
{
	Stack S;
	
	if(MaxStackSize < MinStackSize)
		printf("%s\n","error");
	S = malloc( sizeof(struct StackRecord) );
	if(NULL == S)
		printf("%s\n","error");

	S->Capacity = MaxStackSize;
	S->TopOfStack = EmpytTos;
	S->Array = malloc( sizeof(ElementType) * MaxStackSize );
	if(NULL == S->Array)
		printf("%s\n","error");
	
	return S;
}

void
DisposeStack(Stack S)
{
	if(NULL != S)
	{
		free(S->Array);
		free(S);
	}
}

int
IsEmpty(Stack S)
{
	return S->TopOfStack == EmpytTos;
}

int
IsFull(Stack S)
{
	return S->Capacity == S->TopOfStack + 1;
}

void
MakeEmpty(Stack S)
{
	S->TopOfStack = EmpytTos;
}

void
Push(ElementType x,Stack S)
{
	if(IsFull(S))
		printf("%s\n","error");
	S->Array[++S->TopOfStack] = x;
}

void
Pop(Stack S)
{
	if(IsEmpty(S))
		printf("%s\n","error");
	--S->TopOfStack;
}

ElementType
Top(Stack S)
{
	if(IsEmpty(S))
		printf("%s\n","error");
	return S->Array[S->TopOfStack--];
}

头文件:


#ifndef _Stack_h
#define _Stack_h

struct StackRecord;
typedef struct StackRecord *Stack;
typedef int ElementType;

Stack CreateStack(int MaxElements);
void DisposeStack(Stack S);
void MakeEmpty(Stack S);
int IsFull(Stack S);
int IsEmpty(Stack S);
void Pop(Stack S);
void Push(ElementType x,Stack S);
ElementType Top(Stack S);

#endif
.c文件

测试文件:



#include <stdio.h>
#include "stack.h"

int
main(void)
{
	Stack S;
	S = CreateStack(10);
	Push(2,S);
	printf("%d\n",Top(S));
	return 0;
}



makefile文件:




a.out:stacktest.o stack.o
	gcc -o a.out stacktest.o stack.o
stack.o:stack.c stack.h
	gcc -c stack.h stack.c
stacktest.o:stacktest.c
	gcc -c stacktest.c
clean:
	rm -rf *.o




0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:28554次
    • 积分:965
    • 等级:
    • 排名:千里之外
    • 原创:68篇
    • 转载:20篇
    • 译文:0篇
    • 评论:0条
    文章分类