Advertisement
apl-mhd

stack linked list

Apr 21st, 2017
153
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.01 KB | None | 0 0
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. struct stack{
  5.    
  6.     int data;
  7.     struct stack *next;
  8.    
  9.     };
  10. typedef struct stack stack;
  11.     stack *head;
  12. void push(int x){
  13.    
  14.     stack *temp2;
  15.    
  16.     if(head == NULL){
  17.         head = new stack();
  18.         head->data = x;
  19.         head->next = NULL;         
  20.        
  21.         }
  22.     else{
  23.        
  24.         temp2 = new stack();
  25.         temp2->data=x;
  26.         temp2->next = head;
  27.         head = temp2;
  28.        
  29.         }
  30.    
  31.  
  32.     }
  33.    
  34. int top(){
  35.    
  36.     if(head == NULL){
  37.         cout<<"empty";
  38.     return -1;
  39. }
  40.     return head->data;
  41.    
  42.     }
  43.    
  44. void pop(){
  45.    
  46.     stack *temp = head;
  47.     if(head == NULL){
  48.         cout<<"emtpy\n";
  49.         return;
  50.     }
  51.     if(head->next == NULL){
  52.         head = NULL;
  53.         delete head;
  54.     }
  55.     else{
  56.        
  57.          head = head->next;
  58.          delete temp;
  59.          
  60.         }
  61.    
  62.    
  63.     }
  64.    
  65.    
  66.    
  67. void display(){
  68.     stack *temp = head;
  69.     while(temp !=NULL){
  70.         printf("%d ", temp->data);
  71.         temp = temp->next;
  72.        
  73.         }
  74.     cout<<endl;
  75.     }
  76.  
  77. int main(int argc, char **argv)
  78. {
  79.     head = NULL;
  80.     push(10);
  81.     push(20);  
  82.     push(30);
  83.     push(40);
  84.     display();
  85.     pop();
  86.     display();
  87.     return 0;
  88. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement