スタックのチェーンストレージ実装(シンプルなインスタックとアウトスタック)


/************************************************************************
*
*    :2.2.3.cpp
*
*     :         
*
*    :  fdk

*     :  2018-07-31
*
*    :1.0
*
*     :
*
************************************************************************/
#include 
#include 
using namespace std;

/*     */
typedef struct Node
{
    int data;
    struct Node *next;
}liststrack;

/*      */
liststrack *CreateStack();

/*       */
bool IsEmpty(liststrack *ptrs);

/*  */
void Push(liststrack *strs, int x);

/*  */
int Pop(liststrack *ptrs);

/*  */
void TravelListStrack(liststrack *ptrs);

int main()
{
    liststrack *s; //    liststrack           
    s = CreateStack();
    int i;  //for      
    int a[] = {2, 4, 5, 1, -2, 4, 6, 10};
    int lengths = sizeof(a) / sizeof(a[0]);

    /*         */
    cout << "      :";
    for (i = 0; i < lengths; i++)
    {
        cout << a[i] << " ";
        Push(s, a[i]); //  
    }
    cout << endl;

    /*          */
    cout << "      :";
    while (s->next != NULL)
    {
        cout << Pop(s) << " "; //  
    }
    cout << endl;
    return 0;
}

/*      */
liststrack *CreateStack()
{
    /*          ,     */
    liststrack *s;
    s = (liststrack *)malloc(sizeof(liststrack)); //              
    s->next = NULL;
    return s;
}

/*       */
bool IsEmpty(liststrack *ptrs)
{
    /*   true,    false*/
    if (ptrs == NULL)
    {
        return true;
    }
    else
    {
        return false;
    }
}

/*  */
void Push(liststrack *strs, int x)
{
    /*   x    */
    liststrack *temp;
    temp = (liststrack *)malloc(sizeof(liststrack));  //      
    temp->next = strs->next;
    temp->data = x;
    strs->next = temp;
}

/*  */
int Pop(liststrack *ptrs)
{
    liststrack *first; //    liststrack              
    int temp;
    if (IsEmpty(ptrs))
    {
        cout << "  !" << endl;
        exit(0);                 //      
    }
    /*           */
    first = ptrs->next;
    temp = first->data;
    ptrs->next = first->next;
    free(first);     //    
    return temp;
}