順序棧的創建及操作

#ifndef  _SQ_STACK_  
#define _SQ_STACK_

typedef struct {
	int *base;
	int *top;
	int stack_size;
}SqStack;

#endif // ! _SQ_STACK_


#ifndef _STACKOP_
#define _STACKOP_

void Init_Stack(SqStack *s);
void Destory_Stack(SqStack *s);
void Get_Top(SqStack *s, int *e);
void Push(SqStack *s, int e);
void Pop(SqStack *s, int *e);
void Print_Stack(SqStack s);

#endif // !_STACKOP_

#include <stdio.h>
#include <stdlib.h>
#include "SqStack.h"
#include "StackOp.h"

#define MAX 100		//initial size
#define INCREMENT 10	//incremental size

//top=base作爲棧空的標誌;top指針始終指向棧頂元素的下一個位置
void Init_Stack(SqStack *s) {
	s->base = (int *)malloc(MAX * sizeof(int));	//指針數組操作
	s->top = s->base;
	s->stack_size = MAX;
}

void Destory_Stack(SqStack *s) {
	free(s->base);
}

//非空棧時,返回top-1的棧頂元素的值
void Get_Top(SqStack *s, int *e) {
	if (s->top == s->base) {
		printf("Wrong!\n");
	}
	else {
		*e = *(s->top - 1);
	}
}

void Push(SqStack *s, int e) {	//入棧
	if (s->top - s->base >= s->stack_size) {	//棧滿,加空間
		s->base = (int *)realloc(s->base, (MAX + INCREMENT) * sizeof(int));	//指針數組操作
		s->top = s->base + s->stack_size;
		s->stack_size += INCREMENT;
	}
	*(s->top)++ = e;
}

void Pop(SqStack *s, int *e) {	//出棧
	if (s->top == s->base) {	//空棧
		printf("Wrong!\n");
	}
	else {
		*e = *--(s->top);
	}
}

void Print_Stack(SqStack s) {
	printf("The stack is:\n");
	s.top -= 1;		//top指針指向棧頂元素
	for (; s.top >= s.base; s.top--) {
		printf("%d\n", *s.top);
	}
}

#include <stdio.h>
#include <stdlib.h>
#include "SqStack.h"
#include "StackOp.h"

int main() {
	SqStack stack;
	Init_Stack(&stack);
	int num = 0;
	do {
		printf("input numbers to stack\n");
		scanf("%d", &num);
		if (num != -1) {
			Push(&stack, num);
		}
	} while (num != -1);
	Print_Stack(stack);
	int e = 0;
	Pop(&stack, &e);
	Print_Stack(stack);
	return 0;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章