Topic: Stack
Questions Successfully Completed: 1
1) Implement Stack using Linked List | Easy |
Implementing Stack using Linked List
Question
Input: push(2) push(3) pop() push(4) pop() Output: 3 4 Explanation: push(2) the stack will be {2} push(3) the stack will be {2 3} pop() poped element will be 3, the stack will be {2} push(4) the stack will be {2 4} pop() poped element will be 4
class MyStack
{
// class StackNode {
// int data;
// StackNode next;
// StackNode(int a) {
// data = a;
// next = null;
// }
// }
StackNode top;
//Function to push an integer into the stack.
void push(int a)
{
StackNode s = new StackNode(a);
s.next = top;
top = s;
}
//Function to remove an item from top of the stack.
int pop()
{
if(top==null){return -1;}
int x = top.data;
top = top.next;
return x;
}
}
Thank you for reading :)