仅用一个数组而实现两个栈的例程 除非数组的每一个单元都被使用 否则栈例程不能有溢出声明

数据结构与算法分析——c语言描述 练习3.21 答案


两边向中间增长


stack.h

typedef int ElementType;
#ifndef _stack_h
#define _stack_h

struct StackRecord;
typedef struct StackRecord *Stack;

int IsEmpty1(Stack s);
int IsEmpty2(Stack s);
int IsFull(Stack s);
Stack CreateStack(int MaxElements);
void DisposeStack(Stack s);
void MakeEmpty1(Stack s);
void MakeEmpty2(Stack s);
void Push1(ElementType X, Stack s);
void Push2(ElementType X, Stack s);
ElementType Top1(Stack s);
ElementType Top2(Stack s);
void Pop1(Stack s);
void Pop2(Stack s);
ElementType TopAndPop1(Stack s);
ElementType TopAndPop2(Stack s);
#endif

stack.c

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

#define EmptyTOS1 (-1)
#define MinStackSize (5)

struct StackRecord {
	int Capacity;
	int TopOfStack1;
	int TopOfStack2;
	ElementType *Array;
};

int IsEmpty1(Stack s) {
	return s->TopOfStack1 == EmptyTOS1;
}

int IsEmpty2(Stack s) {
	return s->TopOfStack2 == s->Capacity;
}

int IsFull(Stack s) {
	return s->TopOfStack1 + 1 == s->TopOfStack2;
}

Stack CreateStack(int MaxElements) {
	Stack s;
	if (MaxElements < MinStackSize)
		Error("Stack size is too small");
	s = malloc(sizeof(struct StackRecord));
	if (s == NULL)
		Error("out of space");
	else {
		s->Array = malloc(sizeof(ElementType)*MaxElements);
		if (s->Array == NULL)
			Error("out of space");
		else {
			s->Capacity = MaxElements;
			MakeEmpty1(s);
			MakeEmpty2(s);
		}
	}
	return s;
}

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

void MakeEmpty1(Stack s) {
	s->TopOfStack1 = -1;
}

void MakeEmpty2(Stack s) {
	s->TopOfStack2 = s->Capacity;
}

void Push1(ElementType X, Stack s) {
	if (IsFull(s))
		Error("out of space");
	s->Array[++s->TopOfStack1] = X;
}

void Push2(ElementType X, Stack s) {
	if (IsFull(s))
		Error("out of space");

	s->Array[--s->TopOfStack2] = X;

}


ElementType Top1(Stack s) {
	if (IsEmpty1(s))
		Error("Empty stack");
	return s->Array[s->TopOfStack1];
}

ElementType Top2(Stack s) {
	if (IsEmpty2(s))
		Error("Empty stack");
	return s->Array[s->TopOfStack2];
}

void Pop1(Stack s) {
	if (IsEmpty1(s))
		Error("Empty stack");
	s->TopOfStack1--;
}

void Pop2(Stack s) {
	if (IsEmpty2(s))
		Error("Empty stack");
	s->TopOfStack2++;
}

ElementType TopAndPop1(Stack s) {
	if (IsEmpty1(s))
		Error("empty stack");
	return s->Array[s->TopOfStack1--];
}

ElementType TopAndPop2(Stack s) {
	if (IsEmpty2(s))
		Error("empty stack");
	return s->Array[s->TopOfStack2++];
}


你可能感兴趣的:(仅用一个数组而实现两个栈的例程 除非数组的每一个单元都被使用 否则栈例程不能有溢出声明)