Java: Nth element from the top of the stack
15. Get the nth element from the top of the stack.
Write a Java program to get the nth element from the top of the stack.
Sample Solution:
Java Code:
Sample Output:
Initialize a stack: Input some elements on the stack: Stack elements: 5 4 3 2 1 The 2nd element from the top is 4 The 3rd element from the top is 3 The 4th element from the top is 2
Flowchart:
For more Practice: Solve these Related Problems:
- Write a Java program to retrieve the nth element from the top of a stack without modifying the original stack.
- Write a Java program to implement a recursive method that returns the nth element from the top of a stack.
- Write a Java program to use an auxiliary stack to extract the nth element from the top and then restore the original stack.
- Write a Java program to convert a stack to an array and then retrieve the nth element from the top using stream indexing.
Go to:
PREV : Swap the top two elements of a stack.
NEXT : Get the nth element from the bottom of the stack.
Live Demo:
Java Code Editor:
Improve this sample solution and post your code through Disqus
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.