

Out of range exception for Pop and Top when the corresponding stack is empty.Out of range exception when the stack_id is greater than the number of stacks.We need to handle two types of exceptions: There is no exception handling in the initial solution.There are, however, a few things that can be further improved: The solution above is great, and most candidates (and interviewers!) will be happy with it. } Solution 2: Iterators and Class Templates Updating stack_successor and tops using stack_id. 4) stack_successor pointer to point to the previous element in the stack. 3) next and prev pointers in the linked list. Every node in the ThreeStacks list has: Here is the implementation of the ThreeStacks using a doubly linked list.
#Push function doubly linked list stack free
#Push function doubly linked list stack update
Update the tops array with the stack_successor of the deleted node.The node pointer can be obtained from the tops array. Delete the top node with the given stack_id from the linked list.Update the tops array to replace the existing node (having matching stack_id) with the newly created node.Update the stack_successor pointer of the newly inserted node.Here is how we can modify the Push and Pop methods, using Insert and Delete We also need to keep track of the tops of all the stacks, in an array of pointers.Īt this point, you should be comfortable implementing Insert and Delete method in a doubly linked list given a node pointer. This next-in-stack pointer, or stack_successor allows us to quickly jump to the top of the stack, when the current top is removed (for example by the Pop method). At every node, we also keep a pointer to the next element in the stack with the same stack id!. The head of the list is at the element 2. The diagram shows a doubly linked list with several elements: (2, 4, 3, 1, 100, 10). The basic algorithm should come to you after some thought. Implement three stacks using one Linked List. A command over standard language constructs makes your interview stand out, and gives you an extra edge in the hiring process! This post also adds more robustness to the implementation by using C++ language support (iterators and templates). The problem was asked in an programming interview by Microsoft. This post discusses manipulating a linked list to design stacks.

Data structure manipulation comes up pretty frequently in a programming interview questions.
