數據結構:棧

1.定義算法

  一種能夠實現「先進後出」的存儲結構函數

  棧相似於箱子,往箱子裏面放書,先放進去的最後才能拿出來內存

2.分類it

  靜態棧io

  動態棧變量

3.算法遍歷

  出棧db

  入棧內存分配

4.應用di

  函數調用

  中斷

  表達式求值

  內存分配

  緩衝處理

  迷宮

5.代碼實現

#include <stdio.h>#include <stdlib.h>#include <stdbool.h>//實現棧的功能,先進後出typedef struct Node{    int data;    struct Node * pNext;}NODE, *PNODE;typedef struct Stack{    PNODE pTop;    PNODE pBottom;}STACK, *PSTACK; //STACK 等價於struck Stack*void Init(PSTACK);void push(PSTACK, int);void traverse(PSTACK);bool pop(PSTACK, int * );bool empty(PSTACK);int main(){    int val;    STACK S; //STACK 等價於struct Stack    Init(&S);    push(&S, 1);    push(&S, 2);    push(&S, 3);    push(&S, 4);    push(&S, 5);    push(&S, 6);    traverse(&S); //遍歷輸出    if (pop(&S, &val))    {        printf("出棧成功!出棧的元素是%d\n",val);    }    else    {        printf("出棧失敗!\n");    }    clear(&S);    traverse(&S);    return 0;}void Init(PSTACK pS){    pS->pTop = (PNODE)malloc(sizeof(NODE));    if (NULL == pS->pTop)    {        printf("動態內存分配失敗!\n");        exit(-1);    }    else    {        pS->pBottom = pS->pTop;        pS->pTop->pNext = NULL; // pS->pBottom->pNext = NULL;    }}void push(PSTACK pS, int val){    PNODE pNew = (PNODE)malloc(sizeof(NODE));    pNew->data = val;    pNew->pNext = pS->pTop;    pS->pTop = pNew;    return;}void traverse(PSTACK pS){    if (empty(pS))    {        printf("棧爲空,沒法遍歷");    }    else    {        PNODE p = pS->pTop;        while(p != pS->pBottom)        {            printf("%d ",p->data);            p = p->pNext;        }    }    printf("\n");    // pBottom一直是垃圾值    return;}bool empty(PSTACK pS){    if (pS->pTop == pS->pBottom)    {        return true;    }    else    {        return false;    }}//把pS所指向的棧出棧一次,並把出棧的元素存入pVal形參所指向的變量中,若是出棧失敗,則返回falsebool pop(PSTACK pS, int * pVal){    if (empty(pS)) //pS自己存放的就是S的地址,if(empt返回true則執行return false)    {        return false;    }    else    {        PNODE r = pS->pTop;        *pVal = r->data;        pS->pTop = pS->pTop->pNext;        free(r);        r = NULL;        return true;    }}//clear清空void clear(PSTACK pS){    if (empty(pS))    {        return;    }    else    {        PNODE ClearNode = pS->pTop;        PNODE TempNode = pS->pTop;//        while(ClearNode != pS->pBottom)    //        {//            TempNode = ClearNode->pNext;//            free(ClearNode);//            ClearNode = TempNode;//        }        while(ClearNode != NULL)    //更容易被理解        {            TempNode = ClearNode;            ClearNode = ClearNode->pNext;            free(TempNode);        }        Init(pS);    }}

相關文章
相關標籤/搜索