用單鏈表實現棧並不是最好的方法,因爲出入棧都要涉及指針的操作,在一些情況下這些操作可能會花費過長的時間,最簡單實現棧的方法還是用數組的方式,用一個int型的數字表示棧頂元素的位置,進棧和出棧只需要對這個數字進行自加或自減就可以了。缺點是需要提前知道棧的大小,不支持動態增加棧的容量。
首先,老規矩,聲明結構,類型,和常用例程。
/**
* @file Stack.h
* @brief 用數組實現棧-聲明ADT部分
* @details
* @author [email protected]
* @date 2014-5-20
*/
#include <stdio.h>
#ifndef _Stack_h
//實現棧所需類型和結構
typedef int ElementType;
struct StackRecord;
typedef struct StackRecord *Stack;
//常用例程
int IsEmpty(Stack S); //判空
int IsFull(Stack S); //判滿
Stack CreateStack(int MaxElements); //創建新棧
void DisposeStack(Stack S); //消除棧
void MakeEmpty(Stack S); //置空
void Push(ElementType X,Stack S); //入棧
void Pop(Stack S); //出棧
ElementType TopAndPop(Stack S); //出棧並返回棧頂元素
void FatalError(char *); //錯誤信息
#endif // _Stack_h
接下來是實現部分。
/**
* @file Stack.c
* @brief 用數組實現棧-實現部分
* @details
* @author [email protected]
* @date 2014-5-20
*/
#include <Stack.h>
#include <stdio.h>
#define EmptyTOS (-1) //空棧棧頂位置
#define MinStackSize (5) //最小棧大小
//棧的結構
struct StackRecord
{
int Capacity; //容量,即最大元素個數
int TopOfStack; //棧頂位置
ElementType *Array; //保存棧內元素的數組
};
//錯誤信息
void FatalError(char* str)
{
printf("%s", str);
}
//創建一個棧
Stack CreateStack(int MaxElements)
{
Stack S;
//不能小於規定的最小大小
if (MaxElements < MinStackSize)
FatalError("Stack is too small.");
//爲棧申請空間
S = malloc(sizeof(struct StackRecord));
if (S==NULL)
FatalError("Out of space.");
//爲棧內數組申請空間
S->Array = malloc(sizeof(ElementType)*MaxElements);
if (S->Array == NULL)
FatalError("Out of Space");
S->Capacity = MaxElements;
MakeEmpty(S);
return S;
}
//消除棧
void DisposeStack(Stack S)
{
if (S != NULL)
{
free(S->Array); //先釋放S->Array,若先釋放S則無法引用S->Array
free(S);
}
}
//判斷棧是否爲空
int IsEmpty(Stack S)
{
return S->TopOfStack == EmptyTOS;
}
//判斷棧是否已滿
int IsFull(Stack S)
{
return S->TopOfStack == S->Capacity;
}
//置空棧
void MakeEmpty(Stack S)
{
S->TopOfStack = EmptyTOS;
}
//入棧
void Push(ElementType X, Stack S)
{
if (IsFull(S))
FatalError("Full Stack.");
else
S->Array[++S->TopOfStack] = X;
}
//出棧
void Pop(Stack S)
{
if (IsEmpty(S))
FatalError("Empty Stack");
else
S->TopOfStack--;
}
//出棧並返回棧頂元素
ElementType TopAndPop(Stack S)
{
if (IsEmpty(S))
FatalError("Empty Stack");
else
return S->Array[S->TopOfStack--];
return 0;
}
最後我們在main函數中測試。
/**
* @file main.c
* @brief 用數組實現棧-測試部分
* @details
* @author [email protected]
* @date 2014-5-20
*/
#include <stdio.h>
#include <stdlib.h>
#include <Stack.h>
int main()
{
//向棧中放入3個元素並依次出棧
Stack S = CreateStack(100);
Push(1,S);
Push(2,S);
Push(3,S);
while (!IsEmpty(S))
printf("%d \t", TopAndPop(S));
}
一定要自己敲幾遍才能掌握,多動手纔可能真正弄懂,只看是不行的,學習編程沒有捷徑,必須要一個一個程序得編,一個一個算法得背。