【 資料結構(C語言)】棧——順序實現

來源:互聯網
上載者:User

標籤:kong   儲存空間   des   out   efi   space   結構   語言   資料結構   

棧:棧是一種特殊的線性表。其特殊性在於限定插入和刪除資料元素的操作只能線上性表的一端進行。

/****  2017.11.3**  Ahthor:799**  棧的順序實現*****/#include <bits/stdc++.h>using namespace std;#define STACK_INIT_SIZE 100 /// 儲存空間初始分配#define STACK_INCREMENT 10 /// 儲存空間分配增量#define ElemType int#define Status int#define OK 1#define ERROR -1#define OVERFLOW -2typedef struct{    ElemType *base;    ElemType *top;    int stacksize;} SqStack;Status InitStack (SqStack &S){    S.base = (ElemType * )malloc(STACK_INIT_SIZE * sizeof(ElemType));    if (!S.base) exit(OVERFLOW);    S.top = S.base;    S.stacksize = STACK_INIT_SIZE;    return OK;}Status DestroyStack(SqStack &S){    for (ElemType *index = S.base; index != S.top; index ++)    {        free(index);    }    free(&S);    return OK;}Status ClearStack(SqStack &S){    for (ElemType *index = S.base+1; index != S.top; index ++)    {        free(index);    }    S.top = S.base;    return OK;}Status IsEmptyStack(SqStack &S){    if (S.base == S.top) return true;    else return false;}Status LengthStack(SqStack &S){    return S.top - S.base;}ElemType  GetTop(SqStack &S){    if (S.top == S.base) return ERROR;    ElemType e = *(S.top - 1);    return e;}Status Push(SqStack &S,ElemType &e){    if (S.top - S.base >= S.stacksize)    {        S.base = (ElemType *) realloc (S.base,(S.stacksize + STACK_INCREMENT) * sizeof(ElemType));        if (!S.base)exit(OVERFLOW);        S.top = S.base + S.stacksize;        S.stacksize += STACK_INCREMENT;    }    *S.top = e;    S.top ++;    return OK;}Status Pop(SqStack &S, ElemType &e){    if (S.top == S.base) return ERROR;    e = * --S.top;    return OK;}Status TrverseStack(SqStack &S){    for (ElemType *index = S.base; index != S.top; index ++)    {        cout<<*index<<" ";    }    cout<<endl;    return OK;}int main(){    SqStack * St = (SqStack *) malloc(sizeof(SqStack));    InitStack (*St);    int n;    cin>>n;    while (n--)    {        int tmp;        cin>>tmp;        Push(*St,tmp);    }    int num;    Pop(*St,num);    cout<<" num "<<num<<endl;    TrverseStack(*St);    cout<<" top "<<GetTop(*St)<<endl;    cout<<" len : "<<LengthStack(*St)<<endl;    ClearStack(*St);    if (IsEmptyStack(*St)) cout<<" kong "<<endl;    else cout<<" no "<<endl;    return 0;}

  

【 資料結構(C語言)】棧——順序實現

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.