棧———數組實現

來源:互聯網
上載者:User

標籤:tac   function   操作   個數   思想   top   div   pop   back   

棧(stack)是一種比較基礎的資料結構,其限制了刪除和插入在一個位置操作,而其主要思想就是後進先出(LIFO)。

具體細節可通過代碼看出。

下面給出函數的聲明部分:

StackRecord.h

#ifndef STACKRECORD_H#define STACKRECORD_Htypedef char ElementType;
struct StackRecord;typedef struct StackRecord *Stack;int IsEmpty(Stack S);int IsFull(Stack S);Stack CreateStack(int MaxStackSize);void DisposeStack(Stack S);void MakeEmpty(Stack S);void Push(Stack S, ElementType X);void Pop(Stack S);ElementType Top(Stack S);ElementType PopAndTop(Stack S);#endif

一般的,當我們建立一個棧時都會聲明一個數組來儲存元素,但是這是一個隱含的危險,一般數組大小都會有一個確定的值,而通常我們的程式往往潛在的存在多個棧。因此我們動態申請一個數組,雖然貴這樣花費了昂貴的malloc和free程式時間,但是這很符合我們ADT的想法!

棧的主要常式是Push()和Pop()兩個常式:

StackFunction.c:

#include"StackRecord.h"#include<stdio.h>#include<stdlib.h>#define EmptyStack -1/*預設空棧大小*/#define MinStackSize 5struct StackRecord{    int Capacity;    int TopOfStack;    ElementType *Array;};int IsEmpty(Stack S){    return S->TopOfStack == EmptyStack;}int IsFull(Stack S){    return S->Capacity == S->TopOfStack + 1;/*加1因為數組的大小從0開始*/}Stack CreateStack(int MaxStackSize){    Stack S;    if(MaxStackSize < MinStackSize)        printf("Stack is too small!");    S = (Stack)malloc(sizeof(struct StackRecord));    if(S == NULL)        printf("malloc failure!");    else{
/*Alloc a Arry size you wanted*/ S->Array = (ElementType*)malloc(sizeof(ElementType) * MaxStackSize); if(S->Array == NULL) printf("malloc failure!"); else{ S->Capacity = MaxStackSize; MakeEmpty(S); } } return S;}void MakeEmpty(Stack S){ S->TopOfStack = EmptyStack;}void DisposeStack(Stack S){ if(S != NULL){//if S is NULL, that free(S) is meaningless free(S->Array); free(S); }}void Push(Stack S, ElementType X){ if(IsFull(S)) printf("Stack is full!"); else S->Array[++S->TopOfStack] = X;}void Pop(Stack S){ if(IsEmpty(S)) printf("Stack is empty!"); else S->TopOfStack--;}ElementType Top(Stack S){ if(!IsEmpty(S)) return S->Array[S->TopOfStack]; printf("Stack is empty!"); return 0;//return value used to avoid warning}ElementType PopAndTop(Stack S){ if(!IsEmpty(S)) return S->Array[S->TopOfStack--]; printf("Stack is empty!"); return 0;}

棧———數組實現

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.