Printing a stack with a "for" loop - java

I am trying to print the elements of stack S in reverse (using a "for" loop), but so far I haven't had any success.
I have managed to do it with "pop" fairly easily, but the second way evades me. My solution for "pop" is commented out at the end of the code.
Any help will be appreciated.
PS. Most of this code is irrelevant to the question, but if I knew what and where I can cut out, I probably wouldn't need help at all. Sorry.
package simplearraystackofchars;
public class SimpleArrayStackofchars implements Stack {
protected int capacity; // The actual capacity of the stack array
public static final int CAPACITY = 2; // default array capacity
protected Object S[], K[]; // Generic array used to implement the stack
protected int top = -1; // index for the top of the stack (-1 = empty stack)
public SimpleArrayStackofchars() {
this(CAPACITY); // default capacity
}
public SimpleArrayStackofchars(int cap) {
capacity = cap;
S = new Object[capacity];
}
public int size() {
return (top + 1);
}
public boolean isEmpty() {
return (top == -1);
}
public void push(Object element) throws FullStackException {
if (size() == capacity) {
//throw new FullStackException("Stack is full. Stack size max is "+ capacity);
// can replace previous line with code to double stack size
doubleArray();
}
S[++top] = element;
}
public Object top() throws EmptyStackException {
if (isEmpty()) {
throw new EmptyStackException("Stack is empty.");
}
return S[top];
}
public Object pop() throws EmptyStackException {
Object element;
if (isEmpty()) {
throw new EmptyStackException("Stack is empty.");
}
element = S[top];
S[top--] = null; // dereference S[top] for garbage collection.
return element;
}
private void doubleArray() {
Object[] newArray;
System.out.println("Stack is full (max size was " + capacity + "). Increasing to " + (2 * capacity));
//double variable capacity
capacity = 2 * capacity;
newArray = new Object[capacity];
for (int i = 0; i < S.length; i++) {
newArray[i] = S[i];
}
S = newArray;
}
public static void main(String[] args) {
Stack S = new SimpleArrayStackofchars();
S.push("1");
S.push("2");
S.push("3");
S.push("4");
S.push("5");
S.push("6");
// Stack K is created by popping elements of Stack S from the top.
// This reverses the order.
//
// Stack K = new SimpleArrayStackofchars();
// while (!S.isEmpty()) {
// K.push(S.pop());
// }
// while (!K.isEmpty()) {
// System.out.println(K.pop());
// }
while (!S.isEmpty()) {
System.out.println(S.pop());
}
}
}

Not really sure about what you need that for loop for, but this should produce the same result:
Stack K = new SimpleArrayStackofchars();
for (int i = 0, i < S.size(); i++) {
K.push(S.pop());
}
for (int i = 0, i < K.size(); i++) {
System.out.println(K.pop());
}

Related

thread.main problem with my java interface queue, how to solve it?

I working on my homework assignment, build code to queue with support of interface, I wrote my code but the output hade main.thread issue, to be honest I could not find the issue,however I do believe the issue is from insertion,mainly in the size increment, I appreciate some advice
public class MyQueue implements IntQueue {
private int[] heltal;
private int size;
public void enqueue(int tal) {
// Inserts the specified element into the end of this queue.
// increases the size after every insertion
if (size == 0) {
size++;
heltal[0] = tal;
int[] newArr = new int[heltal.length * 2];
for (int i = 0; i < heltal.length; i++) {
newArr[i] = heltal[i];
}
heltal = newArr;
}
return;
}
public int dequeue() throws NoSuchElementException {
// Returns the head of this queue and removes it.
// Throws an exception if this queue is empty.
if (empty())
throw new NoSuchElementException("The queue is empty");
int NewValue = heltal[0];
for (int i = 1; i < size; i++) {
heltal[i - 1] = heltal[i];
}
heltal[size - 1] = 0;
size--;
return NewValue;
}
#Override
public int peek() throws NoSuchElementException {
// Retrieves, but does not remove, the head of this queue.
// Throws an exception if this queue is empty.
if (empty())
throw new NoSuchElementException("The queue is empty");
return heltal[0];
}
#Override
public boolean empty() {
// Checks if this queue is empty.
return size == 0;
}
}
Initialize your array like below
private int[] heltal = new int[100];
and see if it works

Stack and Queue arrays returning wrong values

I've created stack and queue arrays which hold integers and have a max capacity of ten. I added the values 1-11 and then will remove and print each value until empty. The queue is not only printing 11 values, but also printing 1 instead of 11 for the first value. The stack however is only printing and removing the 10 values but is giving me an IndexOutBoundsException that is not being caught. Any idea why?
Output:
run:
Print queue:
11 2 3 4 5 6 7 8 9 10 11
Print stack:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1
at lab4.Stack.pop(Stack.java:44)
at lab4.Lab4.main(Lab4.java:54)
10 9 8 7 6 5 4 3 2 1
BUILD FAILED (total time: 0 seconds)
Main:
Queue queue = new Queue(10);
Stack stack = new Stack(10);
queue.insert(1);
queue.insert(2);
queue.insert(3);
queue.insert(4);
queue.insert(5);
queue.insert(6);
queue.insert(7);
queue.insert(8);
queue.insert(9);
queue.insert(10);
queue.insert(11);
stack.push(1);
stack.push(2);
stack.push(3);
stack.push(4);
stack.push(5);
stack.push(6);
stack.push(7);
stack.push(8);
stack.push(9);
stack.push(10);
stack.push(11);
System.out.println("Print queue: ");
while (!queue.isEmpty()) {
long n = queue.remove();
System.out.print(n + " ");
}
System.out.println("");
System.out.println("Print stack: ");
while (!stack.isEmpty()) {
Object value = stack.pop();
System.out.print(value + " ");
}
Stack.java
public class Stack {
private int[] stackArray; // Stack array of objects
private int maxSize = 10; // Max size of the stack
private int top; // top integer of stack
public Stack(int maxSize) {
stackArray = new int[maxSize];
top = -1;
}
public boolean isEmpty() {
return (top == maxSize); // true if stack is empty
}
public boolean isFull() {
return (top == maxSize - 1); // true if full
}
public int size() {
return (top + 1); // Return the # of items
}
public void push(int item) // put element into array
{
if (!isFull()) {
top++;
stackArray[top] = item;
}
}
public Object pop() {
if (!isEmpty()) {
top--;
return stackArray[top + 1];
} else
throw new IllegalStateException("Stack empty");
}
public Object peek() {
return stackArray[top];
}
public String toString() {
return "Size: " + maxSize + " Capcaity: " + top; // complete: show the size and capacity
}
}
Queue.java
public class Queue {
private int maxSize = 10;
private int[] queueArray;
private int front;
private int rear;
private int nItems;
// Constructor
public Queue(int s) {
queueArray = new int[maxSize];
front = 0;
rear = -1;
nItems = 0;
}
// Insert item at rear of queue
public void insert(int j) {
if (rear == maxSize - 1) { // Deal with wraparound
rear = -1;
}
queueArray[++rear] = j;
nItems++;
}
public int remove() {
int temp = queueArray[front++];
if (front == maxSize) {
front = 0;
}
nItems--;
return temp;
}
public int peekFront() {
return queueArray[front];
}
public int peekRear() {
return queueArray[front];
}
public boolean isEmpty() {
return (nItems == 0);
}
public boolean isFull() {
return (nItems == maxSize);
}
public int size() {
return nItems;
}
}
These are pretty simple fixes! For the queue, you need to set your maxSize to 11. This will allow you to print each number in the queue correctly without printing the 11 in front. Long story short, given you have 11 total elements in your queue, a max queue size of 11 is necessary.
public class Queue {
private int maxSize = 11;
private int[] queueArray;
private int front;
private int rear;
private int nItems;
}
Now, in terms of your stack, this was also a pretty simple fix. As of right now, your code is returning top == maxSize (or 10) when the stack is empty. This is causing an issue with the pop function. However, when the stack is empty, top should equal -1. So make sure to set top == -1 in the isEmpty() function. You should also change int maxSize = 10 to int maxSize= 11 and make the necessary change in the pop() function as well as this is where the error is occurring. Finally, make sure to change the value in your stack initialization from 10 to 11. I've changed your code and it should now work properly! Enjoy!
public class Stack {
private int[] stackArray; // Stack array of objects
private int maxSize = 11; // Max size of the stack
private int top; // top integer of stack
public Stack(int maxSize) {
stackArray = new int[maxSize];
top = -1;
}
public boolean isEmpty() {
return (top == -1); // true if stack is empty
}
public boolean isFull() {
return (top == maxSize); // true if full
}
public int size() {
return (top-1); // Return the # of items
}
public void push(int item) // put element into array
{
if (!isFull()) {
top++;
stackArray[top] = item;
}
}
public Object pop() {
if (!isEmpty()) {
return stackArray[top--];
} else
throw new IllegalStateException("Stack empty");
}
public Object peek() {
return stackArray[top+1];
}
public String toString() {
return "Size: " + maxSize + " Capcaity: " + top; // complete: show the size and capacity
}

using Java Loop for ArrayList to print each time

I have a method which I basically want to simulate first filling the queue and then after that removing the first person and adding a new person each time in my public void mySimulation() method:
import java.util.*;
public class People {
private final int DEFAULT_CAPACITY = 100;
private int front, rear, count;
private ArrayList<thePeople> people;
private int theMaxCapacity;
//-----------------------------------------------------------------
// Creates an empty queue using the specified capacity.
//-----------------------------------------------------------------
public People(int initialCapacity) {
front = rear = count = 0;
people = new ArrayList<thePeople>(Collections.nCopies(5, (thePeople) null));
}
//-----------------------------------------------------------------
// Adds the specified element to the rear of the queue, expanding
// the capacity of the queue array if necessary.
//-----------------------------------------------------------------
public void enque(thePeople element) {
if (this.isFull()) {
System.out.println("Queue Full");
System.exit(1);
} else {
people.set(rear, element);
rear = rear + 1;
if (rear == people.size()) {
rear = 0;
}
count++;
}
}
//-----------------------------------------------------------------
// Removes the element at the front of the queue and returns a
// reference to it. Throws an EmptyCollectionException if the
// queue is empty.
//-----------------------------------------------------------------
public thePeople dequeue() {
if (isEmpty()) {
System.out.println("Empty Queue");
}
thePeople result = people.get(front);
people.set(front, null);
front = (front + 1) % people.size();
count--;
return result;
}
//-----------------------------------------------------------------
// Returns true if this queue is empty and false otherwise.
//-----------------------------------------------------------------
public boolean isEmpty() {
return (count == 0);
}
//-----------------------------------------------------------------
// Returns the number of elements currently in this queue.
//-----------------------------------------------------------------
public int size() {
return count;
}
public boolean isFull() {
return count == people.size();
}
public void mySimulation() {
Random rand1 = new Random();
thePeople theM = null;
if (this.isFull()) {
this.people.remove(0);
System.out.println("Enqueueing...");
this.enque(people.get(rand1.nextInt(people.size())));
thePeople r1 = people.get(rear - 1);
System.out.println(people.toString());
System.out.println(r1);
for (int e = 0; e < people.size(); e++) {
if (people.get(e) instanceof thePeople) {
System.out.println("G");
} else {
System.out.println("D");
}
}
}
}
//-----------------------------------------------------------------
// Returns a string representation of this queue.
//-----------------------------------------------------------------
#Override
public String toString() {
String result = "";
int scan = 0;
while (scan < count) {
if (people.get(scan) != null) {
result += people.get(scan).toString() + "\n";
}
scan++;
}
return result;
}
public static void main(String[] args) {
People Q1 = new People(25);
thePeople call1 = new thePeople("John King", "001 456 789");
thePeople call2 = new thePeople("Michael Fish", "789 654 321");
Q1.enque(call1);
Q1.enque(call2);
System.out.println(Q1.toString());
ArrayList<thePeople> callerDetails = new ArrayList<>(Arrays.asList(call1, call2));
Random rand = new Random();
for (int z = 0; z <= 4; z++) {
Q1.enque(callerDetails.get(rand.nextInt(callerDetails.size())));
}
System.out.println(Q1.toString());
}
}
any suggestions on how I could repeat this process such that I will first check that the queue is full,
if so remove the first item and add a new person to it using my arrayList each time i my my public void mySimulation() method: as I cant get my head round this at the moment?
Your code is filled with errors:
First make sure you remove the "the" you accidently placed before people in many lines of your code .
Then adjust some of your methods to the right parameters and return types.
As for you question:
it is simple
public void MySimulation(){
if(Queue.isFull()){
Queue.dequeue;}
Queue.enqueue;}

How can I implement a Dynamic Array Stack in Java?

I need to modify a class to create a dynamic array stack.
My code at this point looks something like this:
public class DynamicArrayStack<E> implements Stack<E> {
private E[] elems; //used to store the elements
public static final int defaultIncrement = 25;
private final int increment;
private int top;
#SuppressWarnings( "unchecked" )
public DynamicArrayStack( int increment ) {
this.increment = increment;
elems = (E[]) new Object[ increment ];
top = 0;
}
/**
* Constructor with no parameter that will initialize
* the stack to have an array whose size is the value
* of increment and memorise that value as the value
* of increment.
*/
public void ArraySize() { }
public boolean isEmpty() {
return top == 0;
}
public E peek() {
return elems[ top-1 ];
}
public E pop() {
// save the top element
E saved = elems[ --top ];
// scrub the memory, then decrements top
elems[ top ] = null;
return saved;
}
public void push( E elem ) {
// stores the element at position top, then increments top
elems[ top++ ] = elem;
}
public String toString() {
StringBuffer b;
b = new StringBuffer( "DynamicArrayStack: {" );
for ( int i=top-1; i>=0; i-- ) {
if ( i!=top-1 ) {
b.append( "," );
}
b.append( elems[ i ] );
}
b.append( "}" );
return b.toString();
}
}
How do I edit the first constructor to set increment as the initial size of the stack and that same value to be used when increasing or decreasing the size of the array. My method for doing this seems way too simple. Parameter must be > 0 and a fixed number of cells are added or removed when the size of the array changes.
The second constructor should set the stack to have an array whose size is the value of increment. I keep getting errors here because I can't figure out how to do that because I thought that was already set in the first constructor. Also the size of the array as the value of increment.
Also how do I make this class capable of changing the capacity of the stack and into which method should I place that code?
Here is the simple java code to implement it:
1)Stack based:
public class DynamicArrayStack {
public static void main(String[] args) {
DynamicStack dstack=new DynamicStack(2);
System.out.println("--Pushing--");
dstack.push(1);
dstack.push(2);
dstack.display();
dstack.push(3);
dstack.push(2);
dstack.push(5);
dstack.display();
System.out.println("--Popping--");
dstack.pop();
dstack.pop();
dstack.pop();
dstack.display();
}
}
class DynamicStack {
private int top;
private int capacity;
private int[] array;
public DynamicStack(int cap) {
capacity = cap;
array = new int[capacity];
top = -1;
}
public void push(int data) {
if (isFull()){
expandArray(); //if array is full then increase its capacity
}
array[++top] = data; //insert the data
}
public void expandArray() {
int curr_size = top + 1;
int[] new_array = new int[curr_size * 2];
for(int i=0;i<curr_size;i++){
new_array[i] = array[i];
}
array = new_array; //refer to the new array
capacity = new_array.length;
}
public boolean isFull() {
if (capacity == top+1)
return true;
else
return false;
}
public int pop() {
if (isEmpty()) {
System.out.println("Stack is empty");
return -1;
} else {
reduceSize(); //function to check if size can be reduced
return array[top--];
}
}
public void reduceSize() {
int curr_length = top+1;
if (curr_length < capacity / 2) {
int[] new_array = new int[capacity / 2];
System.arraycopy(array, 0, new_array, 0, new_array.length);
array = new_array;
capacity = new_array.length;
}
}
public boolean isEmpty() {
if (top == -1)
return true;
else
return false;
}
public void display() {
for (int i = 0; i <= top; i++) {
System.out.print(array[i] + "=>");
}
System.out.println();
System.out.println("ARRAY SIZE:" + array.length);
}
}
OUTPUT:
--Pushing--
1=>2=>
ARRAY SIZE:2
1=>2=>3=>2=>5=>
ARRAY SIZE:8
--Popping--
1=>2=>
ARRAY SIZE:4
2)Link List based:
public class LinkListStack {
public static void main(String[] args) {
StackList stack = new StackList();
System.out.println("--Pushing--");
stack.push(1);
stack.push(2);
stack.push(3);
stack.push(4);
stack.push(5);
stack.push(6);
stack.display();
System.out.println("--Popping--");
stack.pop();
stack.pop();
stack.display();
}
}
class Node {
private int data;
private Node next;
public Node(int d) {
data = d;
next = null;
}
public int getData() {
return data;
}
public void setData(int data) {
this.data = data;
}
public Node getNext() {
return next;
}
public void setNext(Node next) {
this.next = next;
}
}
class StackList {
private Node top;
private int length;
public StackList() {
length = 0;
top = null;
}
public void push(int data) {
Node temp = new Node(data);
if (top == null) {
top = temp;
} else {
temp.setNext(top);
top = temp;
}
length++;
}
public int pop() {
Node temp=top;
int data = top.getData();
top = top.getNext();
temp=null;
length--;
return data;
}
public void display() {
Node temp = top;
if (isEmpty()) {
System.out.println("Stack is empty");
} else {
while (temp != null) {
System.out.print(temp.getData() + "=>");
temp = temp.getNext();
}
}
System.out.println();
}
public boolean isEmpty() {
return (top == null);
}
}
OUTPUT:
--Pushing--
6=>5=>4=>3=>2=>1=>
--Popping--
4=>3=>2=>1=>
Default constructor
Your default constructor could simply call your other constructor with a default increment value. For example:
public DynamicArrayStack() {
this(defaultIncrement);
}
Expanding the array
The correct place to expand the array is within the push method. When attempting to add a new element you can check if the array is large enough, and if not create a new larger array. For example you could do the following:
#Override
public E push(final E elem) {
// Check if we need to expand the array
if (elems.length - 1 == top) {
#SuppressWarnings("unchecked")
final E[] newElems = (E[]) new Object[elems.length + increment];
System.arraycopy(elems, 0, newElems, 0, elems.length);
elems = newElems;
}
// stores the element at position top, then increments top
elems[top++] = elem;
return elem;
}
If you want to shrink the array the sensible place to do this would be in the pop() method. You might want to consider only reducing the length when (top + (increment*2))<elems.length to avoid repeatedly copying arrays when you're on the boundary.

Queue array implementation resize

I was required to create a simple queue array implementation with basic methods as enqueue, dequeue, isEmpty, and stuff like that. My only problem is that Im stuck when it comes to the resize method, because if I want to add more values to my queue (with fixed size because is an array) I do not know how to make it work and keep all the values in place.
Everything works just in case you were wondering, the only thing is that doesnt work is my resize (the method wrote in here wasn't the only one I tried).
I'm going to put my main method as well if you want to try it, hope you can help, thanks.
Main Method:
public class MainQueue {
public static void main(String[] args) {
int capacity=10;
Queue<Integer> queue = new Queue<Integer>(capacity);
queue.enqueue(1);
queue.enqueue(2);
queue.enqueue(3);
queue.enqueue(4);
queue.enqueue(5);
queue.enqueue(6);
queue.enqueue(7);
queue.enqueue(8);
queue.enqueue(9);
queue.enqueue(10);
System.out.println("Queue: "+ queue);
//WORKS SO FAR
queue.enqueue(11);
//11 is placed at the beginning of the queue
//instead at the end and my last value is null (?)
Class queue:
import java.util.NoSuchElementException;
public class Queue <E>{
private E[] elements;//array in generic
private int front;//first element or front of the queue
private int back;//last element or back of the queue
private int capacity; //capacity of the queue
private int count; //indicates number of elements currently stored in the queue
#SuppressWarnings("unchecked")
public Queue(int size)
{
capacity = size;
count = 0;
back = size-1;
front = 0;
elements =(E []) new Object[size]; //array empty
}
//Returns true if the queue is empty or false
public boolean isEmpty()
{
return count==0;//means its true
}
//Add elements to the queue
public void enqueue(E item)
{
if(count == capacity)
{
resize(capacity*2);
// System.out.println("Queue is full");
}
back =(back+1) % capacity; //example back=(0+1)%10=1
elements[back]=item;
//elements[0]=0
//item=elements[count];
count++;
}
//Public resize
public void resize(int reSize){
E[] tmp = (E[]) new Object[reSize];
int current = front;
for (int i = 0; i < count; i++)
{
tmp[i] = elements[current];
current = (current + 1) % count;
}
elements = tmp;
}
//Dequeue method to remove head
public E dequeue()
{
if(isEmpty())
throw new NoSuchElementException("Dequeue: Queue is empty");
else
{
count--;
for(int x = 1; x <= count; x++)
{
elements[x-1] = elements[x];
}
capacity--;
return (E) elements;
}
}
//peek the first element
public E peek()
{
if(isEmpty())
{
throw new NoSuchElementException("Peek: Queue is empty");
}
else
return elements[front];
}
//Print queue as string
public String toString()
{
if(isEmpty()) {
System.out.println("Queue is empty.");
//throw new NoSuchElementException("Queue is empty");
}
String s = "[";
for(int i = 0; i <count; i++)
{
if(i != 0)
s += ", ";
s = s + elements[i];// [value1,value2,....]
}
s +="]";
return s;
}
public void delete() { //Delete everything
count = 0;
}
}
you forgot to update stuff when resizing:
front, capacity and back .
public void resize(int reSize){
E[] tmp = (E[]) new Object[reSize];
int current = front;
for (int i = 0; i < count; i++)
{
tmp[i] = elements[current];
current = (current + 1) % count;
}
elements = tmp;
front = 0;
back = count-1;
capacity=reSize;
}
You have few mistakes in resizing when enqueing item which expand queue.
in resize algorithm
current = (current + 1) % count; should be (current + 1) % capacity
You have to change capacity value in resize function
capacity = resize;
Why are you changing capacity when dequeing?

Categories

Resources