使用鏈表實現堆棧


 

 

#include <iostream>
using namespace std;

/***********************************/
/*
棧的鏈式存儲結構實際上是一個單鏈表,叫鏈棧
插入和刪除操作只能在鏈棧的棧頂進行
*/
/***********************************/

#define MaxSize 100

typedef struct Node
{
    int data;
    struct Node *next;
}*pLinkStack, nLinkStack;

//鏈表初始化,創建一個有頭結點的鏈表
pLinkStack CreateLinkStack()
{
    pLinkStack s;
    s = new nLinkStack;
    s->next = NULL;
    return s;
}

int IsEmptyLinkStack(pLinkStack s)
{
    //判斷堆棧s是否為空,若為空則返回1,否則返回0
    return (s->next == NULL);
}

void PushLinkStack(int item, pLinkStack s)
{
    //將元素item壓入堆棧s
    pLinkStack tempCell;
    tempCell = new nLinkStack;
    tempCell->data = item;
    tempCell->next = s->next;
    s->next = tempCell;    //由於頭結點的存在
}

int PopLinkStack(pLinkStack pS)
{
    //刪除並返回堆棧s的棧頂元素
    pLinkStack firstCell;
    int topElem;
    if ( IsEmptyLinkStack(pS) )
    {
        cout << "LinkStack is empty!" << endl;
        return NULL;
    }
    else
    {
        firstCell = pS->next;
        pS->next = firstCell->next;
        topElem = firstCell->data;
        delete firstCell;
        return topElem;
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM