Example of stack program




















Therefore, when the pop method is invoked, the topmost element gets removed, and the stack now looks like the following. Now, 14 has become the topmost element. Therefore, the next calling of the pop method removes the element Then, the next calling of the pop method removes 7, and so on.

At the end, the stack becomes empty. Explanation: By selecting the appropriate methods of the LinkedList class, the above program successfully imitates a stack. After the addition of elements, the linked list looks like the following. Now, element 29 sits at the top and 9 at the bottom. When the removeLast method gets invoked, it removes the last element, i.

Now, element 14 occupies the topmost position. Therefore, on calling the removeLast method removes element 14 from the list. Thus the removeLast method keeps on removing the topmost element eventually, resulting in an empty list. We see that the LinkedList in the above program imitates a stack. Note: We can even implement a queue from the above-mentioned doubly linkedList. Like Article. Python program for implementation of stack import maxsize from sys module Used to return -infinite when stack is empty from sys import maxsize Function to create a stack.

It increases size by 1 def push stack, item : stack. It decreases size by 1 def pop stack : if isEmpty stack : return str -maxsize -1 return minus infinite return stack. WriteLine "Stack is empty" ; return int. WriteLine sll.

Next Stack Set 2 Infix to Postfix. Recommended Articles. Article Contributed By :. Clear ;. Peek ;. WriteLine "Element is found!! WriteLine "Element is not found!! Previous C Hashtable with Examples. Next C Queue with Examples. Recommended Articles. Article Contributed By :. Easy Normal Medium Hard Expert. Writing code in comment?

Please use ide. Load Comments. What's New. Most popular in C. JavaScript for Loop. Functions in JavaScript. JavaScript Objects. Arrays in JavaScript. Calculate the area of a triangle.

Check if a number is odd or even. Find the GCD. Print the Fibonacci series.



0コメント

  • 1000 / 1000