Reversed stack returns one item - java

I have a generic LinkedStack class with a LinkedStack reversed method
It creates a new LinkedStack say newLinkedstack and pushes items from the current stack by popping them. So at the end of the operation the current stack is left empty and newLinkedStack contains the same items/elements that were in "this" stack only in reverse order.
My code compiles but when I create and fill up a stack and then print out the contents,
I only get one result.
public LinkedStack<T> rev()
{
LinkedStack<T> revStack=new LinkedStack<T>();
//final int SIZE=this.size();
while(!(this.empty)){//for(int i=0;i<SIZE;i++)
{
revStack.push(this.pop());
}
return revStack;
}
For example
LinkedStack<String> newLS = new LinkedStack<String>();
newLS.push("noid");
newLS.push("enilec");
newLS.push("River");
newLS.push("Healing");
newLS.push("Pain");
and newLS.rev() returns Pain instead of a reversed stack
UPDATE
Here's my pop method
public T pop()
{
T element=peek();
top=top.next;
return element;
}
I have two push methods this one moves every element from input stack to current stack leaving input stack from argument empty
public void push(LinkedStack<T> stack){
//int SZE = stack.size();
while(!(stack.empty())){//formally for(int i=0;i<SZE;i++){
this.push(stack.pop());}}
Here's my other push method
public void push(T element)
{
top=new Node<T>(item,top);
}

I'm not sure where LinkedStack came from, but it seems that the bug is being caused by that class's implementation.
You'll have to post more source code if you want more specific help.

Related

Creating a queue using a stack in Java

For an assignment, I must create a queue using stacks, but I am not sure what I am doing wrong with this code. I created a primary, alternative, and temporary stack. Every push, I want the value to be added into alternative, and everything currently in primary to be popped into temporary. Then, from temporary, I want all values to be popped into alternative, then change variables so that alternative is the main stack. Now, when I run this to test multiple values entered into the stack, I get an infinite loop with nothing output. I've been stuck on this for a while now so I was hoping I could get some help here. Here's the code.
Stack<Integer> mainStack = new Stack<Integer>();
Stack<Integer> altStack = new Stack<Integer>();
Stack<Integer> tmpStack = new Stack<Integer>();
public void push(int x) {
altStack.add(x);
while (mainStack.empty() == false){
tmpStack.push(mainStack.pop());
}
while(tmpStack.empty() == false) {
altStack.push(tmpStack.pop());
}
mainStack = altStack;
altStack = tmpStack;
}
public int pop() {
return mainStack.pop();
}
public int peek() {
return mainStack.peek();
}
public boolean empty() {
return mainStack.empty();
}
So your idea seems to be to push everything from one stack into another to reverse the order of the elements. I cannot see how you get an infinite loop because you always pop and do it until empty. But two queues are enough to solve this using your idea:
Stack<Integer> mainStack = new Stack<>(); // elements pop in correct order
// the fake queue so to speak
public void push(int x) {
Stack<Integer> stack = new Stack<>(); // temporary stack
// reverse main stack
while (!mainStack.empty())
stack.push(mainStack.pop());
// add x first (at the bottom) of the now empty main stack
mainStack.push(x);
// add the rest of the elements to main stack (preserving original order,
// by reversing the elements again)
while (!stack.empty())
mainStack.push(stack.pop());
}

How can i pop the first added item in the stack in Java?

How should i pop not the last added item in a stack but the first added item ? I tried this but just doesn't work. Thank you
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
public class Exercise0204 {
public static void main(String[] args) {
Stack<String> stack = new Stack<String>();
stack.push("bottom");
System.out.println(stack);
stack.push("second");
System.out.println(stack);
stack.push("third");
System.out.println(stack);
stack.push("fourth");
System.out.println(stack);
List list = new ArrayList(stack);
for (int i = 0; i <stack.size(); i++) {
list.remove(i);
}
}
}
Thank you.
The way to do it if you're stuck with a true stack is to pop everything and immediately push it onto another stack. This will give you a stack with everything in reverse order. Then the top element of the new stack will be the original bottom element.
public E bottomElement(Stack<E> stack) {
if (stack.isEmpty()) throw new IllegalArgumentException("empty stack");
// Flip the stack over.
final Stack<E> upsideDownStack = new Stack<E>();
do {
upsideDownStack.push(stack.pop());
} while (!stack.isEmpty());
final E result = upsideDownStack.peek();
// Flip the stack back over.
do {
stack.push(upsideDownStack.pop());
} while (!upsideDownStack.isEmpty());
return result;
}
If you want to delete the bottom element from the stack rather than only returning it and keeping it in the stack, just change upsideDownStack.peek() to upsideDownStack.pop() and change the final do-while loop to a while loop.
Stack data structure doesn't define behaviour for popping of first element. As noted it is a LIFO data structure. Internal implementation details are not relevant(is it a linked list or something else under the hood) here.
I'd rather use java.util.Deque which is Double Ended Queue.
Deque<String> deque = new LinkedList<>();
deque.push("S1");
deque.push("S2");
deque.push("S3");
deque.push("S4");
deque.push("S5");
deque.push("S6");
deque.push("S7");
deque.push("S8");
String last = deque.pollLast();
String first = deque.pollFirst();
That is not supposed to work, a stack works on the LIFO principle, which means what comes last goes out first. What you might be looking for is a Queue which works on the FIFO principle

Stack push, pop, peek algorithms in Java

I understand how stacks work, but I have to write methods for push, pop and peek and then implement them in a driver class. This is where it gets confusing. Here is my Stack class:
public class Stack implements StackInterface
{
private final int ARRAY_SIZE = 9;
private String[] movies = new String[ARRAY_SIZE]; // Hold movie titles
private int top = 0;
/**
* Constructor
* #param moviesIn
*/
public Stack(String[] moviesIn)
{
movies = moviesIn;
}
/**
* Test for full stack
*/
public void push(String moviesIn)
{
if (top >= movies.length)
System.out.println("ERROR: Stack is full");
top++;
movies[top] = moviesIn;
}
/**
* Test for empty stack
*/
public String pop()
{
if (top == 0) {
System.out.println("ERROR: Stack is empty");
return " ";
}
top--;
return movies[top];
}
public void peek()
{
// ???
}
}
Here is what I have in my main() method so far:
public static void main(String[] args)
{
String[] movies = {"Amour", "*Argo", "Beasts of the Southern Wild", "Django Unchained", "Les Misérables", "Life of Pi", "Lincoln", "Silver Linings Playbook", "Zero Dark Thirty"};
Stack oscarStack = new Stack(movies);
oscarStack.push(movies);
}
I thought I could just pass an object to the stack, but it doesn't seem to work that way. So how do I push the oscarStack object onto the stack? Or do I have to push each string individually? In continuing my online research, it seems a stack constructor can only create an empty stack. Is this why I cannot pass an object argument?
In main, you're placing all of your elements into the backing array implicitly without any push operations. What you'd likely want to do is iterate over the movies you want to push, then push them in.
Two changes should be made:
Change your Stack object to no longer accept an array of Strings. This is confusing and unnecessary as all of the initialization is done on construction.
There are two bugs with your push:
You don't account for the case in which the array is empty. Switch around your incrementation of top, or use movies[top++].
You don't actually prevent code execution if the array is full. You'll get ArrayIndexOutOfBoundsException if you try to run with what you've got.
public static void main(String[] args) {
String[] movies = {"Amour", "*Argo", "Beasts of the Southern Wild", "Django Unchained", "Les Misérables", "Life of Pi", "Lincoln", "Silver Linings Playbook", "Zero Dark Thirty"};
Stack oscarStack = new Stack();
for(String movie : movies) {
oscarStack.push(movie);
}
}
You will have to push each element of the array onto the stack:
for (String movie : movies) {
oscarStack.push(movie);
}
Alternatively, you could write a "pushAll" method in your Stack class that accepts a string array and basically does the same thing.
However, you seem to already be setting the movies array in the constructor, so I don't see the purpose of the call to push. Perhaps you can explain further.
P.S. You seem to have a bug in your push method:
public void push(String moviesIn)
{
if (top >= movies.length)
System.out.println("ERROR: Stack is full");
top++;
movies[top] = moviesIn;
}
With this code, there's no way that movies[0] will ever be assigned a value.
The push method expects a string as an argument and not an array of strings so you can either change the push method to accept string arrays as argument or pass one string at a time to your current push method.
Also you are not pushing oscarStack object and if you want to push any object the again the method signature should support that.
Apart from the answers given here, also remember to null the reference that was popped from the stack.
Here is a quote from the book 'Effective Java '
Generally speaking, whenever a class manages its own memory, the
programmer should be alert for memory leaks. Whenever an element is
freed, any object references contained in the element should be nulled
out.
A sample copied from the book:
public Object pop() {
if (size==0) throw new EmptyStackException();
Object result = elements[--size];
elements[size] = null; // Eliminate obsolete reference
return result;
}
If you want to use Stack data structure and you don't want to incur the cost of Synchronization then you can use Dequeue. Stack class available in Java extends Vector.
Deque<Integer> q=new LinkedList<Integer>();
q.offerFirst(Integer.SIZE);
q.offerFirst(Integer.SIZE);
q.pollFirst();
This is the most efficient stack implementation that is available in Java collection framework.
You should probably initialize your variable as top=-1.Note that I have not initialized a constructor for this class Stack since its not compulsory to do so.If no user-defined constructor is provided for a class, compiler initializes member variables to its default values.
1.numeric data types are set to 0.
2.char data types are set to null character(‘\0’).
3.reference variables are set to null.
Here is how the full code should be implemented:-
public static void main(String[] args)
{
String[] movies = {"Amour", "*Argo", "Beasts of the Southern Wild", "Django Unchained", "Les Misérables", "Life of Pi", "Lincoln", "Silver Linings Playbook", "Zero Dark Thirty"};
Stack oscarStack = new Stack();
for (String movie:movies){
oscarStack.push(movie);
}
}
public class Stack implements StackInterface
{
private final int ARRAY_SIZE = MAX_SIZE;
private String[] movies = new String[ARRAY_SIZE]; // Hold movie titles
private int top = -1;
/**
* Test for full stack
*/
public void push(String moviesIn)
{
if (top >= movies.length)
System.out.println("ERROR: Stack is full");
return;
top++;
movies[top] = moviesIn;
}
/**
* Test for empty stack
*/
public String pop()
{
if (top == -1) {
System.out.println("ERROR: Stack is empty");
return " ";
}
top--;
return movies[top];
}
public void peek()
{
if(top==-1){
System.out.println("ERROR: Stack is empty");
return " ";
}
else{
return(movies[top]);
} }}

Return the stack element at a given index without modifying the original Stack in Java

Ok I was recently asked this in an interview, and I am intrigued. Basically I have a stack with a certain set of values, I want to pass the stack object in a function and return the value at certain index. The catch here is that after the function is complete, I need the stack unmodified; which is tricky because Java passes reference by value for objects. I am curious if there is purely a java way to do using push(), pop(), peek(), isempty() and primitive data type. I am against copying the elements into an array or string. Currently the cleanest I have got is using clone, find the code below:
import java.util.Stack;
public class helloWorld {
public int getStackElement( Stack<Integer> stack, int index ){
int foundValue=null;//save the value that needs to be returned
int position=0; //counter to match the index
Stack<Integer> altStack = (Stack<Integer>) stack.clone();//the clone of the original stack
while(position<index)
{
System.out.println(altStack.pop());
position++;
}
foundValue=altStack.peek();
return foundValue;
}
public static void main(String args[]){
Stack<Integer> stack = new Stack<Integer>();
stack.push(10);
stack.push(20);
stack.push(30);
stack.push(40);
stack.push(50);
stack.push(60);
helloWorld obj= new helloWorld();
System.out.println("value is-"+obj.getStackElement(stack,4));
System.out.println("stack is "+stack);
}
}
I understand that cloning is also copying, but that's the basic flaw I am aiming to remove. Stripped down I am asking if I would be actually be able to pass the stack's value instead of passing the value of its reference.
Thanks in advance.
int position =5;
Integer result = stack.get(position);
Java Doc here
If you cannot use another stack, you can cheat and abuse a local variable on the call stack for the same purpose by making a recursive method:
public static <T> T getStackElement(Stack<T> stack, int index) {
if (index == 0) {
return stack.peek();
}
T x = stack.pop();
try {
return getStackElement(stack, index - 1);
} finally {
stack.push(x);
}
}

returning middle element in stack

I have to create a method peek MidElement , so as return the middle element of the stack .
So do I have to use an ArrayList, or TORTOISE-HARE algo .
The following is my Class , which has a method named peekMidElement.
How do I reference Size() to the ArrayList .
When I compile the following , I am getting IndexOutOFBoundsExcption at ArrayList.RangeCheck(UnknownSource) & at ArrayList.get(UnknownSource)
public class SortableStack<E extends Comparable<E>> implements ISortableStack<E> {
private int N;
private Node first;
private ArrayList<E> listOne = new ArrayList<E>();
/* I have to reference the Stack to array list
which I am going use for finding the size of the stack */
public boolean isEmpty() {
return first == null;
}
public int size() {
return N;
}
public E peekMidElement() {
if(listOne.size() <= 0){
throw new EmptyStackException();
}
return listOne.get(listOne.size()/2);
}
I cannot see how the code snippet you gave can throw an IndexOutOfBoundsExcption at the point you have indicated. I conclude that:
the code snippet is not the actual code (e.g. it has been spliced together from a larger class, leaving out some crucial details), or
the exception is not thrown at the place you indicated, or
... this class (which is not thread-safe) is being used in a multi-threaded application without adequate synchronization. The scenario is that some other thread deletes a bunch of elements from listOne at exactly the wrong moment. This unlikely, and if it was the cause, the failure would only occur very occasionally.

Categories

Resources