1. 程式人生 > >資料結構-C語言實現線性棧

資料結構-C語言實現線性棧

#include<stdio.h>
#include<stdlib.h>
#define STACK_INIT_SIZE 100//儲存空間初始化分配量
#define STACKINCREAMENT 10//儲存空間分配增量
#define OK 1
#define OVERFLOW -1
#define FALSE 0
#define TURE 1
#define ERROR -1
typedef int Status;
typedef struct
{
	int *base;//在棧構造之前和銷燬之後,base的值為NULL
	int *top;//棧頂指標
	int stacksize;//當前已分配的儲存空間,以元素為單位
}SqStack;
//初始化棧
Status InitStack(SqStack *s)
{
	s->base=(int *)malloc(STACK_INIT_SIZE*sizeof(int));
	if(!s->base)exit(OVERFLOW);//儲存分配失敗
	s->top=s->base;
	s->stacksize=STACK_INIT_SIZE;
	return OK;
}
//獲取棧頂元素
Status GetTop(SqStack s,int *e)
{
	if(s.top==s.base)
		return ERROR;
	*e=*(s.top-1);
	return OK;
}
//壓棧
Status Push(SqStack *s,int e)
{
	if(s->top-s->base>=s->stacksize)//棧滿
	{
		s->base=(int *)realloc(s->base,(s->stacksize+STACKINCREAMENT)*sizeof(int));
		if(!s->base)exit(OVERFLOW);//儲存分配失敗
		s->top=s->base+s->stacksize;
		s->stacksize+=STACKINCREAMENT;
	}
	*s->top=e;
	*s->top++;
	return OK;
}
//出棧
Status Pop(SqStack *s,int *e)
{
	if(s->base==s->top)
		return ERROR;
	*s->top--;//先移動棧頂指標,再賦值
	*e=*s->top;
	return OK;
}
//棧長度
int StackLength(SqStack s)
{
	return s.top-s.base;
}
//判斷棧是否為空
Status StackEmpty(SqStack s)
{
	return s.base==s.top?OK:FALSE;
}
//清空順序棧
Status CleanStack(SqStack *s){
s->top=s->base;
return OK;
}

void main()
{
	int ch=1;
	SqStack s;
	InitStack(&s);
	while(ch!=0)
	{
		system("cls");
		printf("1.初始化棧\t2.棧的長度\t3.棧的判空\n4.獲取棧頂元素\t5.壓棧\t6.出棧\n7.清空棧\n0.退出\n");
		printf("請選擇:\n");
		scanf("%d",&ch);
		switch(ch)
		{
		case 0:printf("byebye!\n");
			break;
		case 1:{
				InitStack(&s);
				printf("初始化成功\n");
				break;
			   }
		case 2:
			{
				int length;
				length=StackLength(s);
				printf("棧的長度為%d\n",length);
				break;
			}
		case 3:
			{
				if(StackEmpty(s)==OK)
					printf("棧為空\n");
				else
					printf("棧不為空\n");
				break;
			}
		case 4:
			{
				int e;
				GetTop(s,&e);
				printf("棧頂元素為:%d\n",e);
				break;
			}
		case 5:
			{
				int e;
				printf("請輸入你要壓棧的數值:\n");
				scanf("%d",&e);
				if(Push(&s,e)==OK)
				printf("壓棧成功\n");
				else
					printf("壓棧失敗\n");
				break;
			}
		case 6:
			{
				int e;
				if(Pop(&s,&e)==OK)
				printf("元素為:%d\n",e);
				else
					printf("出棧失敗\n");
				break;
			}
		case 7:
			{
				if(CleanStack(&s)==OK)
					printf("清空成功\n");
				else
					printf("清空失敗\n");
				 break;
			}
		default:
			printf("輸入錯誤,請重新輸入\n");
			break;
		}
		system("pause");
	}
}

在這裡插入圖片描述