We need to implement a versioned stack, i.e. version of stack will increment after each push/pop. Apart from push/pop, implement a method print(n) which would print stack state corresponding to version 'n'. For example:
-> initially stack is empty.
-> Version 1: 11 is pushed
-> Version 2: 8 is pushed
-> version 3: pop. only 11 left
-> Version 4: 15 is pushed
....
And so on.
Print(n) should print state at version 'n'.
Here 1 should print 11, 2 should print 8, 11...
All methods should be as efficient as possible.
Approach:
Implement the stack as the singly link list where each node contains the data and ptr to the next node.
Create a versionHashMap<Integer, Node>, versionHashMap stores the version and points to the latest node of the stack.
Ex:
version stack-nodes
v0 => null
push 9
v1 => 9->null
push 10
v2 => 10->9->null
push 11
v3 => 11->10->9->null
pop 11
v4 => 10->9->null
push 12
v5 => 12=>10->9->null
Now at version 4 the this is how the stack would look like in memory:
v5 v3 v4,v2 v1 v0
| | || | |
12 -> 11 -> 10 -> 9 -> null
Output for below code:
Version::0
null
Version::1
9 -> null
Version::2
10 -> 9 -> null
Version::3
11 -> 10 -> 9 -> null
Version::4
10 -> 9 -> null
Version::5
12 -> 10 -> 9 -> null
Version::6
10 -> 9 -> null
Version::7
9 -> null
Version::8
null
No comments:
Post a Comment