資料結構:實現一個棧,並完成各個介面的實現
阿新 • • 發佈:2018-12-20
實現一個棧
棧的概念
棧:一種特殊的線性表,其只允許在固定的一端進行插入和刪除元素操作。進行資料插入和刪除操作的一端 稱為棧頂,另一端稱為棧底。棧中的資料元素遵守 後進先出 LIFO(Last In First Out)的原則。 壓棧:棧的插入操作叫做進棧/壓棧/入棧,入資料在棧頂。 出棧:棧的刪除操作叫做出棧。出資料也在棧頂。
棧的實現
棧的實現一般可以使用陣列或者連結串列實現,相對而言陣列的結構實現更優一些。因為陣列在尾上插入資料的 代價比較小。 具體程式碼如下:
Stack.h
#pragma once #include <stdio.h> #include <stdlib.h> #include <assert.h> #include <malloc.h> typedef int STDateType; typedef struct Stack { STDateType* _a; int _top; int _capacity; }Stack; void StackInit(Stack* ps,int n); void StackPush(Stack* ps, STDateType x);//入資料 void StackPop(Stack* ps);//出資料 STDateType* StackTop(Stack* ps);//取棧頂的資料 int StackSize(Stack* ps);//返回棧中資料個數 //0為空,1為非空 int StackEmpty(Stack* ps);//判斷是否為空 void TestStack();
Stack.c
#include "Stack.h" void StackInit(Stack* ps, int n)//初始化棧 { assert(ps); ps->_a =(STDateType*) malloc(sizeof(STDateType)*n); ps->_capacity = n; ps->_top = 0; } void StackPush(Stack* ps, STDateType x)//入資料 { assert(ps); //判斷是否需要增容 if (ps->_capacity = ps->_top) { ps->_a = realloc(ps->_a, ps->_capacity * 2 * sizeof(STDateType)); ps->_capacity = ps->_capacity * 2; } ps->_a[ps->_top] = x; ps->_top++; } void StackPop(Stack* ps)//出資料 { assert(ps); if (ps->_top > 0) { ps->_top--; } } STDateType* StackTop(Stack* ps)//取棧頂的資料 { assert(ps); return ps->_a[ps->_top-1]; } int StackSize(Stack* ps)//返回棧中資料個數 { assert(ps); return ps->_top; } int StackEmpty(Stack* ps)//判斷是否為空 { assert(ps); return ps->_top == 0 ? 0 : 1; } void TestStack() { Stack sl; StackInit(&sl,3); StackPush(&sl, 1); StackPush(&sl, 2); StackPush(&sl, 3); StackPush(&sl, 4); StackPush(&sl, 5); while (StackEmpty(&sl))//當棧不為空 { printf("| %d |\n", StackTop(&sl));//取棧頂資料 printf("-----------\n"); StackPop(&sl);//出棧頂資料 } }
Main.c
#include "Stack.h"
int main()
{
TestStack();
system("pause");
return 0;
}