Tuesday, 3 November 2015

CPP Program for implementing stack as linked list - Data Structures

#include<iostream>
using namespace std;
struct node
{
int data;
struct node *link;
};
struct node *top=NULL;

void push(int val)
{
node *newnode =new node;
newnode->data=val;
newnode->link=top;
top=newnode;
}

void pop()
{
if(top==NULL)
cout<<"\nStack is empty!";
else
top=top->link;
}


void display()
{
node *temp=top;
if(temp==NULL)
cout<<"\nStack is empty!";
else
{
while(temp!=NULL)
{
  cout<<temp->data<<"\n";//to print horizontally we need to point from bottom, hence to avoid this we print vertically..
  temp=temp->link;
}
}
}

int main()
{
int choice,val;
while(1)
{
cout<<"\nSTACK LINKED LIST \n1.Push 2.Pop 3.Display 4.Exit \nEnter your choice:";
cin>>choice;
switch(choice)
{
case 1:
   cout<<"\nEnter value to Push:";cin>>val;
   push(val);
   break;
case 2:
   pop();
   break;
case 3:
   display();
   break;
case 4:
   return 0;
   break;
default:
cout<<"\nCheck ur input\n";
}
}
return 0;
}



OUTPUT:

STACK LINKED LIST
1.Push 2.Pop 3.Display 4.Exit
Enter your choice:1

Enter value to Push:1

STACK LINKED LIST
1.Push 2.Pop 3.Display 4.Exit
Enter your choice:1

Enter value to Push:5

STACK LINKED LIST
1.Push 2.Pop 3.Display 4.Exit
Enter your choice:1

Enter value to Push:3

STACK LINKED LIST
1.Push 2.Pop 3.Display 4.Exit
Enter your choice:3
3
5
1

STACK LINKED LIST
1.Push 2.Pop 3.Display 4.Exit
Enter your choice:2

STACK LINKED LIST
1.Push 2.Pop 3.Display 4.Exit
Enter your choice:3
5
1

STACK LINKED LIST
1.Push 2.Pop 3.Display 4.Exit
Enter your choice:

No comments:

Post a Comment