Stack Overflow Asked by Anish Raj on December 18, 2021
In Java, how to delete element from the bottom of the stack? Should I use a temporary stack and pop every element into it to reverse the stack and then pop the first element or would treating it as a list would be easier? I am trying to delete first n/2 elements from the bottom of the stack where n is the number of element in the stack. here I am taking only Integer values.
I understand your problem and easiest solution for this is to use remove(int i) function. This takes int as a parameter,
Stack<Integer> = new Stack<>();
//suppose stack is [1,2,3,4,5,6,7,8]
First use size() to get stack size. To delete first n/2 elements -
int size = (int) Math.floor(stack.size()/2)
Now, run a loop from 0 to size Be carefull always delete first element as every time stack gets updated
for(int i = 0; i<size ; i++) {
stack.remove(0);
}
Print the remaining stack
System.out.println(stack) //[5,6,7,8]
I hope this solves your doubt.
Answered by Akash Kulkarni on December 18, 2021
Based on your described use case, I think you need a different data structure.
I would recommend you to review the double-ended queue, or Deque
, which has been part of the Java Collections API since Java 1.6.
This data structure is a bit of a hybrid between a Stack and a Queue, permitting you to add/remove elements to/from either end.
You can perform the traditional Stack operations of push and pop using addFirst
and removeFirst
, respectively.
To remove from the tail - or 'bottom' of the 'Stack', as you put it - you can use removeLast
.
The size
method will give you the number of elements.
Answered by Philip Wrage on December 18, 2021
You can use Deque in java. It supports both insertion and deletion on both sides. e.g.
Deque<Integer> deque = new ArrayDeque<>(Arrays.asList(1,2,3,4));
int count = deque.size() / 2;
while (count > 0)
{
deque.removeLast();
count--;
}
You can use linkedList as implementation of Deque instead. The difference between LinkedList and ArrayDeque: https://stackoverflow.com/questions/6163166/why-is-arraydeque-better-than-linkedlist#:~:text=Key%20differences%3A,LinkedList%20but%20not%20in%20ArrayDeque&text=The%20LinkedList%20implementation%20consumes%20more%20memory%20than%20the%20ArrayDeque
More details at https://docs.oracle.com/javase/8/docs/api/java/util/Deque.html
Answered by Pitbull_Owen on December 18, 2021
Get help from others!
Recent Answers
Recent Questions
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP