Using java.util.Stack.iterator to display contents the stack - java

In the code below I pushed 1,5,3 into the stack respectively means the top 3 is located at the top of stack and 1 at the bottom( which is the case) however when i use iterator to display the contents of the stack, the iterator apparently treats stack like queue and
instead of displaying
3<-5<-1<-Bottom!
it outputs:
1<-5<-3<-Bottom!
why does the iterator do this?
If that's natural behavior of iterator then how can i display the contents of a Stack without using pop?
import java.util.Iterator;
import java.util.Stack;
public class MyStack{
Stack<Integer> stack = new Stack<>();
public void display(){
Iterator <Integer> it = stack.iterator();
while(it.hasNext()){
System.out.print(it.next()+"<-");
}
System.out.println("Bottom!");
}
void pushAll(int [] data){
for(int i:data){
stack.push(i);
}
}
public static void main(String [] org){
MyStack stak= new MyStack();
stak.pushAll(new int [] {1,5,3});
stak.display();
}
}
Console:
1<-5<-3<-Bottom!
while it should output:
3<-5<-1<-Bottom!

The hacky way would be to use a listIterator and start it from the end :
ListIterator<Integer> it = stack.listIterator(stack.size());
while(it.hasPrevious()){
System.out.print(it.previous()+"<-");
}
System.out.println("Bottom!");

You ... don't. The iterator only goes one way (specifically, the same way as in Vector which is where it comes from since Stack is a subclass of Vector).
Technically you can get around this with the ListIterator but really this is one of the reasons the javadoc recommends not using the Stack class anymore.
Use a class with the Deque interface (such as an ArrayDeque) as recommended and you then have the descendingIterator() call.
Iterator<Integer> it = arrayDeque.descendingIterator();
while(it.hasNext()){
System.out.print(it.next()+"<-");
}

Related

How to add another linked list objects

I a homework where I need to merge two linkedlist, "songs" list and "artists" linked list, it works on the first list the "song" list, but whenever i add another list it just wont work
as you can see here the public static void now has errors
package mergedlinkedlist;
import java.util.LinkedList;
public class Mergedlinkedlist {
public static void main(String[] args) {
LinkedList<String>song = new LinkedList<>();
song.add("imagine");
song.add("bohemian rhapsody");
song.add("highway to hell");
System.out.println(song);
}
public static void main(String[] args) {
LinkedList<String>artists = new LinkedList<>();
artists.add("john lennon");
artists.add("queen");
artists.add("ACDC");
System.out.println(artists);
}
Okey, as one comment has pointed out, no program can have 2 main methods. You cannot create another one.
I suggest to integrate the code from your second into your first. You can safely just add the contents together.
The task is to merge the lists. Do you need any more help with that?
Assuming the task says you know the size of the list you can just create a new list and use the same method you used above to add them to the list. If you do not, you will need to use a loop. It would look like this:
LinkedList<String>artistsAndSongs = new LinkedList<>();
if (artists.size() == songs.size()) {
for (int i = 0; i < artists.size(); i++) {
artistsAndSongs.add(artists.get(i));
artistsAndSongs.add(songs.get(i));
}
} else {
System.out.println("Not every artist is matched with a song!");
}
But you should read up on how linked lists work exactly in the documentation. This will not only improve your understanding of the class but also teach you how to quickly find solutions to your problem.
https://docs.oracle.com/javase/7/docs/api/java/util/LinkedList.html

Truncating A Java Stack

I have a Stack<String> defined in Java that I use for navigation through a workflow.
What I would like to do is ensure that all values in the stack are unique: when a transition to a "previous" state occurs, I want to remove everything off the stack AFTER the first occurrence of the previous state in the stack.
Is there an easy way to do this?
Edit: More information was requested. Here's an example of the contents of a stack:
[state2, state3, state2, state1, startState]
I need the ability to accept a String, check the stack and see if there are multiple occurrences of it, then pop elements until the "bottommost" occurrence of that String. "Truncate" was probably a bad description of what I wanted to do... "pop until I hit an arbitrary index" is probably closer to what I need.
Consider using deque. Below is the link which explains why should you use it over stack.
Why should I use Deque over Stack?
Stack implements List (among various other interfaces). Get a ListIterator for the last element, and move it backwards until you find an occurrence of the new state, counting how many elements along the way, and then pop that many elements. (If you don't find the new state, then of course you don't pop anything, and you push the new state onto the stack instead).
This might not be particularly efficient, but it will certainly work. If you also want it to be efficient, you probably need to use another data structure (either instead of or as well as the stack). One possibility is to use a Map (in addition to the stack) to keep track of which states are on the stack together with the index at which they occur, or at least a Set to keep track of which states are on the stack (you can then just pop states until you find the one you are looking for). You would maintain the stack and the map or set in parallel.
Or if you were serious about:
"pop until I hit an arbitrary index" is probably closer to what I need.
... then surely this would suffice:
int numberToPop = stack.size() - arbitraryIndex - 1;
while (numberToPop-- > 0) {
stack.pop();
}
Would it simplify your overall code if you created your own container that is basically a set that's a stack? Something like (not a complete implementation):
public class StackSet<T> {
private final Set<T> set;
private final Deque<T> queue;
public StackSet(){
set = new HashSet<>();
queue = new ArrayDeque<>();
}
public void push(T value){
if(set.add(value)){
queue.push(value);
}
}
public T pop(){
return queue.pop();
}
}
That should guarantee no duplicates.
Here's an example of a truncate method with Deque instead of Stack.
import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.Collection;
import java.util.Deque;
public class ExampleDeque
{
public static void main(String[] args)
{
Deque<String> deque = new ArrayDeque<String>();
deque.offer("startState");
deque.offer("state1");
deque.offer("state2");
deque.offer("state3");
deque.offer("state2");
System.out.println("Before");
print(deque);
deque = truncate(deque, "state2");
System.out.println("After");
print(deque);
}
static Deque<String> truncate (Deque<String> deque, String value)
{
if(!deque.contains(value)) return deque;
String[] array = deque.toArray(new String[deque.size()]);
for(int i = 0; i < array.length; i++)
{
if(array[i] == value)
{
String[] truncated = Arrays.copyOfRange(array, 0, i + 1);
Collection<String> collection = Arrays.asList(truncated);
return new ArrayDeque<>(collection);
}
}
return null;
}
static void print(Deque<String> deque)
{
for(String s : deque)
System.out.println(s);
System.out.println();
}
}

How to print a stack in Java

I wrote a method that receives a queue as a parameter and then convert this queue into a stack. Now I want to try to print this method in the main to see if it works, but there isn't any toString method for stacks.
I already did some research and tried to convert stacks into arrays, but I can't get it to work. Printing the stack values in Java
How can I do this?
public static void QueueStack(Queue<Integer> q){
Stack<Integer> stack1 = new Stack<Integer>();
while(!q.isEmpty()){
int temp = q.dequeue();
stack1.push(temp);
}
Arrays.toString(stack1.toArray());
}
Did you try using the Stack classes' toString() method?
e.g.
stack1.toString();
Or was there a specific format you want to print out?
You could try the get(int index) method of the Vector class which Stack extends, assuming you don't want to pop the elements from your stack while you print them.
if (!tack1.isEmpty()) {
for(Object a : stack1) {
System.out.println(a);
}
}
Here, is a method to convert a given Queue to Stack:
public static void QueueStack(Queue<Integer> queue){
Stack<Integer> stack = new Stack<>();
for(Integer in: queue){
stack.push(in);
}
//Here, the output would be same as you inserted elements.As stack uses iterator which prints elements as they are inserted(a bug in stack iteration)
System.out.println("Stack: "+stack);
//You can use java 8 for-each style as well.
stack.forEach(System.out::println);
//If you want to traverse stack in LIFO manner..
while(stack.isEmpty){
System.ou.println(stack.pop());
}
//For better performance ArrayDeque<>() is preferred!
Deque<Integer> stack = new ArrayDeque<Integer>();
}
You could also do it very similar to how to initialized it.
while(!stack1.isEmpty())
{
int t = stack1.pop();
System.out.println(t);
}

Method to copy a stack into a new one and return it without changing the original stack using a single queue using standard API classes [duplicate]

This question already has answers here:
How do I copy a stack in Java?
(6 answers)
Closed 5 years ago.
Ok, so I tried making a method that does what I wrote in the title. It should be pretty clear to see what's happening. However, I feel like I'm making it more complicated than it should be. I copy the stack into the queue, resulting in it being backwards: [4,3,2,1]
Then I copy it back into the stack, and then back into the queue so that I can get it in proper order: [1,2,3,4]
Then I peek into the copiedStack, and remove into the original stack.
Then I return the copiedStack.
My main method prints this:
[1,2,3,4]
[1,2,3,4]
^ (btw, anyone know how to properly align the code above? it's annoying me)
So is there a simpler implementation?
The methods I can use are here:
http://docs.oracle.com/javase/7/docs/api/java/util/Queue.html
http://docs.oracle.com/javase/7/docs/api/java/util/Stack.html
import java.util.*;
public class Question2Stack {
public static void main(String[] args) {
Stack<Integer> stack = new Stack<Integer>();
stack.push(1);
stack.push(2);
stack.push(3);
stack.push(4);
System.out.println(copyStack(stack));
System.out.println(stack);
}
public static Stack<Integer> copyStack(Stack<Integer> stack) {
Stack<Integer> copiedStack = new Stack<Integer>();
Queue<Integer> q = new LinkedList<Integer>();
while (!stack.isEmpty()) {
q.add(stack.pop());
}
while (!q.isEmpty()) {
stack.push(q.remove());
}
while (!stack.isEmpty()) {
q.add(stack.pop());
}
while (!q.isEmpty()) {
copiedStack.push(q.peek());
stack.push(q.remove());
}
return copiedStack;
}
}
Stack is a Collection, and collections can addAll(Collection)
Stack<Integer> intStackCopy = new Stack<Integer>();
intStackCopy.addAll(origStack);
You can also simply iterate:
Iterator<Integer> intItr = origStack.iterator();
while(intItr.hasNext()) {
intStackCopy.push(intItr.next());
}
If you absolutely have to use a 'Queue':
public Stack<Integer> copyStack(Stack<Integer> orig) {
Queue<Integer> q = new Queue<Integer>();
q.addAll(orig);
Stack<Integer> intStackCopy = new Stack<Integer>();
intStackCopy.addAll(q);
return intStackCopy;
}
You can do this redundant Queue with any of the approaches in my or #Chamil's answer. The original does not need to be restored in any way, because it is never altered.
Stack<Integer> copiedStack = (Stack)intStack.clone();
The Stack class implements clonable interface. the clone method will clone your stack and return the reference to the new stack.

Populating stack causes error

I'm populating a stack instance variable with elements of the array el, but in the line below it's giving me an error although I specified that it's a stack of Integers.
Error:
Incompatible types - found java.util.Stack but expected java.lang.Integer...
Code:
import java.util.Stack;
public class SortedStack
{
private Stack<Integer> stack = new Stack<Integer>();
public SortedStack(Integer[] el)
{
for(int i = 0; i < el.length; i++)
{
el[i] = stack; /** THIS LINE*/
}
}
}
To add an item to the top of the stack, use the push method.
Example:
public SortedStack(Integer[] el)
{
for(int i = 0; i < el.length; i++)
{
stack.push(el[i]);
}
}
This will push elements from the el array into the stack.
I think you want to add elements of el into stack . You were trying to assign stack object to el[i] which is not possible. Its obvious that you got error.
So your code should be like following :
public class SortedStack
{
private Stack<Integer> stack = new Stack<Integer>();
public SortedStack(Integer[] el)
{
for(int i = 0; i < el.length; i++)
{
stack.push(el[i];
}
}
}
I'm not a Java developer but I'm guessing if you want to put a value on the stack you'll need something like:
stack.push(el[i]);
The reason for your error is your trying to assign the i-th Element in an Integer array, to be a Stack. This is failing because it can't cast a Stack to an integer.
Use Stack.push() method.
stack.push(el[i]);
To use a stack, you want to push() your item on top of it, and pop() it from the stack when you're ready to use it again. In your case, it seems more appropriate to inherit the stack, than to wrap it.
import java.util.Stack;
public class SortedStack extends Stack<Integer>
{
public SortedStack(Integer[] el) // Why "Sorted"? You're not sorting here...
{
for(int i = 0; i < el.length; i++)
{
this.push(el[i]); /** THE ERROR IS THIS LINE */
}
}
}
Doing this, you can use your SortedStack just like any regular stack, with the addition of adding a whole range of elements in the constructor. You might also want to implement a PushRange() method, that can be called after the object is instantiated.

Categories