1. 程式人生 > >鏈棧實現

鏈棧實現

#include"stdafx.h" #include<iostream> using namespace std; struct Node; typedef struct Node *PNode;  struct Node {     int data;     PNode node; };  struct LinkStack  {      PNode top;  }; typedef struct  LinkStack *PListStack; PListStack Chushi() {     PListStack pl = (PListStack)malloc(sizeof(struct Node));     if (pl!=NULL)     {         pl->top= NULL;         return pl;     }     else     {         cout << "Out of Space!" << endl;         return NULL;     } } int Empty(PListStack pl) {     return pl->top == NULL; } int Push(PListStack pl,int x) {     PNode a = (PNode)malloc(sizeof(struct Node));     if (a==NULL)     {         cout << "Out of Space" << endl;         return 0;     }     else     {         a->data = x;         a->node = pl->top;         pl->top = a;         return 1;     } } int Pop(PListStack pl) {     PNode a;     if (Empty(pl))     {         cout << "This is Empty Stack" << endl;         return 0;     }     else {         a = pl->top;         cout << "Leaving stack elements:"<<pl->top->data << endl;         pl->top = a->node;         free(a);         return 1;     } } int GetTop(PListStack pl) {     if (Empty(pl))     {         cout << "Nothing in Stack" << endl;     }     else     {         return pl->top->data;     }    } int main() {     PListStack p = Chushi();     int item;     cout << "Please enter the stack element to end at 0." << endl;     while (true)     {         cin >> item;         if (item)         {             Push(p, item);         }         else         {             break;         }     }     cout<< "Stack Top:"<<GetTop(p) <<endl;     Pop(p);     return 0; }

//ALIN  END