# 10998 - Stack ```cpp #include <iostream> #include <cstring> //#include "function.h" using namespace std; /* function.h */ class ListNode { private: int data; ListNode *nextPtr; ListNode *prevPtr; public: ListNode( const int &info ) //constructor : data( info ), nextPtr( NULL ), prevPtr( NULL ){ } friend class List_stack; //make List_stack a friend }; class List_stack { private: ListNode *head; ListNode *tail; public: List_stack(); ~List_stack(); void push(const int &); void pop(); void print(); }; /* main.c */ int main(){ List_stack L_stack; char command[10]; int n; while(cin>>command){ if(strcmp(command,"pop")==0){ L_stack.pop(); }else if(strcmp(command,"push")==0){ cin >> n; L_stack.push(n); }else if(strcmp(command, "print") == 0){ L_stack.print(); cout << endl; } } return 0; } /* function.c */ /* List_stack */ /* constructor */ List_stack::List_stack(){ tail = NULL; head = NULL; } /* destructor */ // since there are movable memories // we need to delete it manually List_stack::~List_stack(){ while(tail != head){ tail = tail->prevPtr; delete tail->nextPtr; } delete tail; } // Special Case: head = NULL void List_stack::push(const int &k){ if(head == NULL){ head = new ListNode(k); tail = head; } else{ tail->nextPtr = new ListNode(k); tail->nextPtr->prevPtr = tail; tail = tail->nextPtr; } } // Special Case: Only one node (tail = head) void List_stack::pop(){ if(tail != head){ tail = tail->prevPtr; delete tail->nextPtr; } else if(head != NULL){ delete head; tail = head = NULL; } } // Print from tail to head void List_stack::print(){ ListNode *Lp = tail; if(Lp != NULL){ while(Lp != head){ cout << Lp->data << ' '; Lp = Lp->prevPtr; } cout << Lp->data; } } ```
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up