Implementation-based problems
0% completed
Implement Stack with Linked List
Design a stack that supports getMin() in O(1) time and O(1) extra space
Two Stacks
Queue Using Stack
Stack using queue
16

Implement Stack With Linked List

Difficulty: MEDIUM
Contributed By
Ankit Kharb
Avg. time to solve
30 min
Success Rate
73%

Problem Statement
Suggest Edit

You need to implement the Stack data structure using a Singly Linked List.

Create a class named 'Stack' which supports the following operations(all in O(1) time):


getSize: Returns an integer. Gets the current size of the stack

isEmpty: Returns a boolean. Gets whether the stack is empty

push: Returns nothing. Accepts an integer. Puts that integer at the top of the stack

pop: Returns nothing. Removes the top element of the stack. Does nothing if the stack is empty.

getTop: Returns an integer. Gets the top element of the stack. Returns -1 if the stack is empty

Input format:

The first line of the input will contain the number of queries, 'T'.
The next 'T' lines will contain the queries. They can be of the following five types:

'1': Print the current size of the stack

'2': Find whether the stack is empty. Print "true" if yes, "false" otherwise

'3': This query will be given like "3 val" where val can be any non-negative integer. Put val on the top of the stack. Print nothing

'4': Remove the top element of the stack. Print nothing

'5': Print the top element of the stack. If the stack is empty, print -1

Output format:

For each test case, print the result of each query on a separate line. If the query is '3' or '4', print nothing (not even an empty line)

The output of each test case will be printed in a separate line.

Note:

You do not need to print anything, it has already been taken care of. Just implement the given function.
Constraints:
1 <= T <= 10^6
1 <= Q <= 5
1 <= Data <= 2^31 - 1

Where 'Q' is the type of query and 'Data' being the values getting pushed and popped from the stack. 

Time Limit: 1sec
Sample Input 1:
4
3 5
3 4
1
2
Sample Output 1:
2
false    
Explanation for Sample Output 1:
The first two queries ('3') push 5 and 4 on the stack. So the size of stack becomes 2. Therefore the third query ('1') prints the size and since the stack is not empty, the fourth and final query ('2') outputs "false"
Sample Input 2:
4
3 5
3 4
4
5
Sample Output 2:
5   
Explanation for Sample Output 2:
The first two queries ('3') push 5 and 4 on the stack. The third query ('4') removes the top element of the stack which is 4 and the fourth and final query ('5') print the top element of the stack, 5
Reset Code
Full screen
copy-code
Console