printing stack without popping elements java - java

for a task I have to write a method which prints the stack, that part is easy
public void print(stack s)
{
while(!isEmpty())
{
System.out.println(s.peek());
s.pop();
}
}
The problem is that after I printed the stack, my task is to print the bottom element on the stack, which isn't there any more cause I used s.pop() in my print method. This is my code for printing the bottom element.
public void bottom(stack s)
{
if(isEmpty())
{
System.out.println("Stack is empty");
}
else
{
System.out.println(stackArray[0]);
}
}
My question is: How should i modifie the print method so I don't have to pop the elements from the stack? Or is there another way to make it so that the stack still holds my elements after using print method?
as resquested this is the stack we're using in our classes(most of it is in dutch):
public class MyStack
{
protected Object[ ] stackArray;
protected int top;
private int grootte;
private static final int DEFAULT_GROOTTE = 10;
public MyStack( )
{
grootte = DEFAULT_GROOTTE;
stackArray = new Object[grootte];
top = 0;
}
public boolean isEmpty( )
{
if (top == 0)
return true;
else
return false;
}
public void push(Object e)
{
if (top == grootte)
allocateMore( );
stackArray[top] = e;
top++;
}
public Object pop( )
{
if(isEmpty( ))
{
System.out.println("Stack leeg : er kan geen element van de stack afgehaald worden.");
return null;
}
top--;
return stackArray[top];
}
public Object peek( )
{
if(isEmpty( ))
{
System.out.println("Stack leeg : er kan geen topelement van de stack getoond worden.");
return null;
}
return stackArray[top-1];
}
public int size( )
{
return top;
}
private void allocateMore( )
{
Object[ ] original = stackArray;
grootte = grootte * 2;
stackArray = new Object[ grootte];
for(int i = 0; i < grootte/2; i++)
{
stackArray[i] = original[i];
}
}
}
since my rep isn't high enough to answer my own question a quick edit
I think I've found an other way to print the stack using this
public void print(stack s)
{
for(int i =top-1; i>=0;i--)
System.out.println(stackArray[i]);
}
it probably isn't the best way to do it, but it's working :P

If you use the built-in java.util.Stack type, then this derives from Vector, so you can use getElement(int) to read elements at any stack depth.
If this is your own code, you will have to add a method to do the same.
Alternatively, you can pop the elements into another stack or a List type and then rebuild the stack after printing but that would be very inefficient and your teacher will most probably frown about such a solution.

There is a simple workaround if you just want to see the contents without any fancy stuff.
System.out.println(Arrays.toString(myStack.toArray()));

if (!_stack.empty())
Check whether the Stack is Empty
for(int i=_stack.size()-1; i>=0;i--)
System.out.println(_stack.get(i));
getting stack values

Use Iterator to loop through the Stack, as they work on any Collection object.

Related

How to remove(pop) element from a stack implementation?

Currently working on my home assignment, a simulation code to make stack with a support of dynamic array.
The method pop() is not working to it is function, I wrote some of the code but I need a completion. My stack should be simulates like this, you insert a numbers to be called top then remove that number(top).
import java.util.NoSuchElementException;
public class MyStack implements IntStack {
int[] heltal;
public MyStack() {
heltal = new int[0];
}
public void push(int tal) {
int[] temp = new int[heltal.length + 1];
for (int x = 0; x < heltal.length; x++) {
temp[x] = heltal[x] + tal;
}
heltal = temp;
for (int i = 0; i < heltal.length; i++) {
heltal[i] = tal;
}
}
#Override
public int pop() {
if (Isempty()) {
throw new NoSuchElementException("The stack is empty, there is nothing to pop");
} else {
int[] temp = new int[heltal.length - 1];
for (int x = 0; x < heltal.length - 1; x++) {
temp[x] = heltal[x];
}
int etttal = heltal[0];
heltal = temp;
return etttal;
}
}
#Override
public int peek() {
if (Isempty()) {
throw new NoSuchElementException("The stack is empty");
} else {
return heltal[0];
}
}
public boolean Isempty() {
return heltal.length == 0;
}
}
You appear to be making this more difficult than required. For a stack implementation, push, pop, peek, and others are nothing more than index manipulators that return or store a value. The stack can be backed by an array or a list. And pushing et al are abstract terms. So when you push a value, you do not need to copy everything down by one. Just add it to the end of your data structure.
pop - check the index and if valid, return the element at the current index, update the index.
push - store the value at the next location. Probably index + 1 but it depends on how you implement it.
peek - return the top value (at the index) but don't update the index.
If you are using an array, you need to add method(s) to increase it's capacity.
For more information, check out Stack
Here is a simple push method, backed by an array called stack and an index field. It presumes ints are being used.
public void push(int v) {
if (index == stack.length-1) {
// no more room, increase array size
// while retaining current values.
}
stack[++index] = v;
}

Does assigning an object to another mean that instant variables will aslo change?

I am trying to to create a stacks which has the following API:
Stacks(int n)// creates stacks of size n
pop() //returns the last element pushed in the stacks
pop(int n) //returns an array of of n elements
push(int e) //appends an element to the stacks
push(int n, ar[]) //appends an array to the stack
The stacks should be able to dynamically change size when needed, so client programs dont have to do it every time.
I have done all that only my problem is when assigning object A to object B doesn't that mean that A will now points to the address of B?
Here is my code and i hope it explaines what i mean
public class Stacks {
/*
* constructs a stack object
* #param n that will determine that size of the stacks to be constructed
*/
public Stacks(int n)
{
this.elemetns= new int[n];
this.size=n;
this.top=-1;
}
/*
* constructs a stack object, with size of 2 when no parameter is given
*/
public Stacks()
{
this.elemetns= new int[2];
this.size=2;
this.top=-1;
}
public int pop()
{
if (top<0)
{
System.out.println("Error code 2: Empty stacks");
return -1;
}
else
{
int n= this.elemetns[top];
top--;
return n;
}
}
public int [] pop(int size)
{
if (this.size<size)
{
System.out.println("Error code 3: The Maximum number of elements that can be acquired is "+ this.size);
return null;
}
else
{
int res[]= new int[size];
for (int i=0;i<size;i++)
{
res[i]=pop();
}
return res;
}
}
public void push(int e)
{
if (!isFull())
{
this.elemetns[++top]=e;
System.out.println(e+" has been pushed to the stack ");
}
else
{
updateStacksSize(this);
this.elemetns[++top]=e;
System.out.println(e+" has been pushed to the stack ");
}
}
public void push(int n,int [] ar)
{
for (int i=0;i<n;i++)
this.push(ar[i]);
}
private void updateStacksSize(Stacks s)
{
int newSize= s.top*2;
Stacks newStacks= new Stacks(newSize);
for (int i = s.top; i>-1;i--)
newStacks.elemetns[i]=s.pop();
s= newStacks;//shouldnt newStacks get garbage collected
//and s gets the new address and attributes of newStacks?
}
private boolean isFull(){return this.size==(this.top+1);}
public static void main(String[] args)
{
Stacks s= new Stacks(5);
for (int i=0;i<7;i++)
s.push(i+1);
System.out.println();
int []arr= s.pop(6);
for (int i=0;i<arr.length;i++){
System.out.println(arr[i]);
}
}
private int elemetns[];
private int top;
private int size;
}
Why does running this program results in problem with the old size although the current object's has been updated.
one more question is it possible to assign this= newStacks instead of instantiating new Stacks object
In Java you assign object references to variables.
I have done all that only my problem is when assigning object A to object B doesn't that mean that A will now points to the address of B?
s= newStacks;//shouldnt newStacks get garbage collected
//and s gets the new address and attributes of newStacks?
It is the other way around since the assignment in Java is from right to left.
"I have done all that only my problem is when assigning object A to object B doesn't that mean that A will now points to the address of B?"
if this is what you meant then:
Stacks A = new Stacks();
Stacks B = A;
Then what this means is that B is now pointing to A.
You're kinda over do it. A stack should consist of a chain of nodes, like an singel-linked list of nodes. I've written an example on this below, see if you can see how it works.
public class Stack <E> {
private StackItem<E> currTop;
private int size;
private int max;
private static class StackItem<E> {
private E e;
private StackItem<E> next;
}
public Stack(int max) {
currTop = null;
size = 0;
this.max = max;
}
public void add(E e){
if ((size+1) == max) throw new StackOverflowError("Max items in stack is reached");
StackItem<E> old = currTop;
currTop = new StackItem<>();
currTop.e = e;
currTop.next = old;
size++;
}
public E getFirst() {
if (currTop == null) return null;
E output = currTop.e;
currTop = currTop.next;
size --;
return output;
}
public E showFirst() {
return currTop.e;
}
public int getSize() {
return size;
}
}

JAVA - How do you push a string into a stack?

I have an assignment to push Strings into a stack. I created a program that will store numbers but I cannot figure out the correct way to define the array to take a string. Here is my code. My Java is rusty so I am trying to remember all this from my first java class 2 years ago. I am sure it is super simple but I cannot find anything online where strings are stored in a stack for me to see how to do it. Thanks for the help!
public class stackx {
private int maxSize; //number of items in stack
private int[] stackArray;
private int top; // top of stack
public stackx(int arraySize) {
maxSize = arraySize;
stackArray = new int[maxSize];
top = -1;
}
public void push(int a) { //put value on top of stack
if (top == maxSize - 1)
{
System.out.println("Stack is full");
} else {
top = top + 1;
stackArray[top] = a;
}
}
public int pop() { //take item from top of stack
if (!isEmpty())
return stackArray[top--]; // access item, decrement top
else {
System.out.println("Stack is Empty");
}
}
public int peek() //peek at the top of the stack
{
return stackArray[top];
}
public boolean isEmpty() { //true if stack is empty
return top == -1;
}
public void display() {
for (int i = 0; i <= top; i++) {
System.out.print(stackArray[i] + " ");
}
System.out.println();
}
} // End class stackx
**Driver class Here**
public class practicestack {
public static void main(String[] args) {
stackx newStack = new stackx(5);
newStack.push(redShirt);
newStack.push(greenShirt);
newStack.push(yellowPants);
newStack.push(purpleSocks);
newStack.push(pinkSocks);
stackx.peek();
//Display the Full Stack
newStack.display();
//Test removing a value using pop method
newStack.pop();
newStack.display();
}
}
This should be easy, I will provide you a small hint, if you still can't figure it out, I will post entire code
when you declare something like this
private int[] stackArray;
and use this array to push and pop your items, as this is Integer array you can only use this implementation for Integers.
Now your requirement is to push and pop Strings, so essentially you should do something like this.
private String[] stackArray;
Note : Your Push and pop method will change likewise, those will be small changes
Hope this helps!
Good luck.
Your stack only takes ints. You need it to take Objects if you want to store anything at all. Java doesn't let you manipulate pointers, so you can't just use int like in C/C++. You could also use generics, e.g. public class stackx<T>, which would give you something like stackx<String> newStack = new stackx<>(5);.
Just modify int to String.Here is the Demo.

Generic array index out of bounds

Ok , here is my problem . I'm learing to use generic classes and methods. I want to make an generic array list and method that will add/remove element by choosen index. I simply doesn't know how to do that . My example is calling an IndexOutOfBoundsException.
Any help is welcome.
Thanks it advance .
class klasa3:
public class klasa3<E> {
private java.util.ArrayList<E> list = new java.util.ArrayList<>();
public klasa3(int initSize){
}
public int getSize() {
return list.size();
}
public E peek() {
return list.get(getSize() - 1);
}
public void push(E o,int indeks) {
o = list.get(indeks);
list.add(o);
}
public E pop(int indeks) {
E o = list.get(indeks);
list.remove(indeks);
return o;
}
public boolean isEmpty() {
return list.isEmpty();
}
#Override
public String toString() {
return "stack: " + list.toString();
}
}
main class:
public class klasa2 {
public static void main(String[] args ) {
klasa3 stak2 = new klasa3(13);
stak2.push("cola",2); // problem here
stak2.pop(2);
System.out.println(stak2.getSize());
}
}
You're creating an empty ArrayList, and then trying to get the third element (element at index 2) from it within your push method. That's not going to work.
Now, you're currently ignoring your initSize parameter in your constructor. You might want something like:
// TODO: Rename the class to follow naming conventions
public klasa3(int initSize) {
for (int i = 0; i < initSize; i++) {
list.add(null);
}
}
Or provide a default element:
// TODO: Rename the class to follow naming conventions
public klasa3(int initSize, E element) {
for (int i = 0; i < initSize; i++) {
list.add(element);
}
}
This is what is happening:
In the main method you first create a new klasa3 object. Then you call push("cola", 2) on it.
The push method does: o = list.get(indeks), where indeks is 2. At this point the list is empty, so 2 is not a valid index, which causes an IndexOutOfBoundsException.
The index that you pass to the get method must be between 0 (inclusive) and the size of the list (exclusive). Since the size is 0, the index 2 is invalid.

Is there a way to add multiple strings to a stack without using a push method each time

I am working on a program to help student learn all the presidents in order. I am using a stack. I want to create a stack with all of the presidents in order. Then the user will enter a president name and the program will compare there input with the top of the stack.
I want to know if there is a way to fill my stack with Strings without using the .push method 44 times?
Here is what I have so far in my main:
package namepresidents;
import java.util.Scanner;
public class NamePresidents {
public static void main(String[] args)
{
BoundedStackInterface<String> presidents;
presidents = new ArrayStack<String>(41);
presidents.push("George Washington");
String menu = "Would you like to study: \n"
+ "1. All the presidents \n"
+ "2. The first half \n"
+ "3. The second half \n"
+ "0. Exit \n";
Scanner in = new Scanner(System.in);
int option = in.nextInt();
}
}
Here is my ArrayStack class for references:
package namepresidents;
public class ArrayStack<T> implements BoundedStackInterface<T> {
protected final int DEFCAP= 43;
protected T[] stack; //holds stack of elemets
protected int topIndex = -1;
public ArrayStack(){ // default constructor
stack = (T[]) new Object[DEFCAP];
}
public ArrayStack(int maxSize){ // constructor with user defined array size
stack = (T[]) new Object[maxSize];
}
public void push(T element){
//throws excption if the stack is full
//otherwise places element on top of stack
if (!isFull())
{
topIndex++;
stack[topIndex] = element;
}
else
{
throw new StackOverflowException("Push attempted on a full stack.");
}
}
public boolean isFull(){
//returns true if the stack is full
if (topIndex == stack.length-1)
{
return true;
}
else
{
return false;
}
}
public boolean isEmpty(){
//returns true if the stack is empty
if (topIndex == -1)
{
return true;
}
else
{
return false;
}
}
public void pop(){
//throws excption if the stack is full
//otherwise places element on top of stack
if (!isEmpty())
{
stack[topIndex] = null;
topIndex--;
}
else
{
throw new StackUnderflowException("Pop attempted on an empty stack.");
}
}
public T top(){
//throws excption if the stack is full
//otherwise returns element on top of stack
T topOfStack = null;
if (!isEmpty())
{
topOfStack = stack[topIndex];
}
else
{
throw new StackUnderflowException("Top attempted on an empty stack.");
}
return topOfStack;
}
}
Since the ArrayStack is a class that you implemented and it don't support that feature, your answer is no.
But you could add one push method to ArrayStack that accepte a list like this:
public void push(List<T> elements) {
for(T element : elements) {
push(element);
}
}

Categories