c語言實現數據結構--棧

是一種特殊的線性表,只能在一端進行插入刪除操作,具有先進後出的特點。
進行插入刪除操作的一端稱爲棧頂,另一端稱爲棧底!
接下來就用C語言來實現一下棧的基本操作:
代碼實現:

/*
stack.h文件,包含了棧定義和操作函數的聲明。
*/
#pragma once
#ifndef _STACK_H_
#define _STACK_H_

#define STACK_SIZE 20
typedef int STDataType;
typedef struct Stack 
{
	STDataType* _a;
	int _top;       // 棧頂
	int _capacity;  // 容量 
}Stack;

void StackInit(Stack* ps);//初始化棧
void StackDestory(Stack* ps);//銷燬
void StackPush(Stack* ps, STDataType x);//入棧
void StackPop(Stack* ps);//出棧
STDataType StackTop(Stack* ps);//取棧頂元素
int StackEmpty(Stack* ps);//判斷是否爲	空棧
int StackSize(Stack* ps);//返回棧中元素個數
void StackPrint(Stack* ps);//打印棧
void TestStack();//測試函數
#endif
/*
stack.c文件,包含所有函數的實現和主函數
*/
#include"stack.h"
#include<stdio.h>
#include<assert.h>
#include<stdlib.h>
#include<string.h>
void StackInit(Stack* ps)
{
	assert(ps != NULL);
	ps->_a = (STDataType*)malloc(sizeof(STDataType)*STACK_SIZE);
	if (!ps->_a)
	{
		return;//內存分配失敗!
	}
	memset(ps->_a, 0, STACK_SIZE);
	ps->_capacity = STACK_SIZE;
	ps->_top = 0;
}
void StackDestory(Stack* ps)
{
	assert(ps != NULL);
	if (ps->_a)
	{
		free(ps->_a);
		ps->_a = NULL;
	}
	ps->_capacity = 0;
	ps->_top = 0;
}
void StackPush(Stack* ps, STDataType x)
{
	assert(ps != NULL);
	if (ps->_capacity == ps->_top + 1)
	{
		STDataType*tmp = (STDataType*)realloc(ps->_a, ps->_capacity * 2);//棧空間不足,擴容
		if (tmp == NULL)
		{
			return;//擴容失敗,返回,入棧失敗!
		}
		ps->_a = tmp;
		ps->_capacity *= 2;
	}
	ps->_a[ps->_top] = x;
	ps->_top++;
}
void StackPop(Stack* ps)
{
	assert(ps != NULL && ps->_top!=0);
	ps->_top--;
}
STDataType StackTop(Stack* ps)
{
	assert(ps != NULL && ps->_top != 0);
	return ps->_a[ps->_top-1];
}
int StackEmpty(Stack* ps)
{
	assert(ps != NULL);
	return ps->_top == 0;
}
int StackSize(Stack* ps)
{
	assert(ps != NULL);
	return ps->_top;
}
void StackPrint(Stack* ps)
{
	assert(ps != NULL);
	for (int i = ps->_top-1; i>=0; i--)
	{
		printf("| %d |\n", ps->_a[i]);
		printf("-----\n");
	}
	putchar('\n');
}
void TestStack()
{
	Stack st;
	StackInit(&st);
	StackPrint(&st);
	printf("是否爲空棧? %d\n", StackEmpty(&st));
	printf("棧中元素個數爲:%d\n", StackSize(&st));
	StackPush(&st, 0);
	StackPush(&st, 1);
	StackPush(&st, 2);
	StackPush(&st, 3);
	StackPush(&st, 4);
	StackPrint(&st);
	StackPop(&st);
	StackPrint(&st);
	printf("棧頂元素爲:%d\n", StackTop(&st));
	printf("是否爲空棧? %d\n", StackEmpty(&st));
	printf("棧中元素個數爲:%d\n", StackSize(&st));
	StackDestory(&st);
}
int main()
{
	TestStack();
	return 0;
}

棧是一種比較簡單的數據結構,但是它在一些其他算法問題和實際應用的解決中有着不可小視的作用。

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