Can someone explain what am I doing wrong here ?
I am trying to create a queue from two stacks as per a book exercise. I get error "Stack Underflow" from the peek function. But everything seems right to me :P Please explain. Thanks!
//Program to implement Queue using two Stacks.
import java.util.NoSuchElementException;
public class Ex3_5_Stack {
int N;
int countOfNodes=0;
private Node first;
class Node {
private int item;
private Node next;
}
public Ex3_5_Stack() {
first=null;
N=0;
}
public int size() {
return N;
}
public boolean isEmpty() {
return first==null;
}
public void push(int item){
if (this.countOfNodes>=3) {
Ex3_5_Stack stack = new Ex3_5_Stack();
stack.first.item=item;
N++;
} else {
Node oldfirst = first;
first = new Node();
first.item=item;
first.next=oldfirst;
N++;
}
}
public int pop() {
if (this.isEmpty())
throw new NoSuchElementException("Stack Underflow");
int item = first.item;
first=first.next;
return item;
}
public int peek() {
if (this.isEmpty())
throw new NoSuchElementException("Stack Underflow");
return first.item;
}
}
And MyQueue file
public class Ex3_5_MyQueue {
Ex3_5_Stack StackNewest,StackOldest;
public Ex3_5_MyQueue() {
super();
StackNewest = new Ex3_5_Stack();
StackOldest = new Ex3_5_Stack();
}
public int size() {
return StackNewest.size()+StackOldest.size();
}
public void add(int value) {
StackNewest.push(value);
}
private void transferStack() {
if (StackOldest.isEmpty()) {
while (StackNewest.isEmpty()) {
StackOldest.push(StackNewest.pop());
}
}
}
public int peek() {
this.transferStack();
return StackOldest.peek();
}
public int remove() {
this.transferStack();
return StackOldest.pop();
}
public static void main(String[] args) {
Ex3_5_MyQueue myQueue = new Ex3_5_MyQueue();
myQueue.add(4);
myQueue.add(3);
myQueue.add(5);
myQueue.add(1);
System.out.println(myQueue.peek());
}
}
In transferStack(), you're missing an exclamation mark. It should be:
private void transferStack(){
if(StackOldest.isEmpty()){
while(!StackNewest.isEmpty()){ // you forgot it here
StackOldest.push(StackNewest.pop());
}
}
}
Related
public class StackSimple{
private long capacity=1000;//maximum size of array
private int idx_top;
private Object data[];
public StackSimple(int capacity)
{
idx_top=-1;
this.capacity=capacity;
data = new Object[capacity];
}
public boolean isEmpty(){
return(idx_top<0);
}
public boolean isFull(){
return(idx_top>=capacity-1);
}
public int size()
{
return idx_top+1;
}
public boolean push(Object x){
if (isFull()){
throw new IllegalArgumentException("ERROR:Stack Overflow.Full Stack");
}
else
{`enter code here`data[++idx_top]=x;
return true;
}
}
public Object pop(){
if(isEmpty())
throw new IllegalArgumentException("ERROR:Stack Underflow.Empty Stack.");
else{
return data[idx_top--];
}
}
public Object top(){
if (isEmpty())
throw new IllegalArgumentException("ERROR:Stack Underflow.Empty Stack.");
else{
return data[idx_top];
}
}
public void print()
{`
for (int i=size()-1;i>=0;i--)
System.out.println(data[i]);
}
}
public class Stack_Exercise {
public static void main(String[] args) {
StackSimple s = new StackSimple(capacity:3);//error shows here
s.push(x:"books");`enter code here`
s.push(x:"something");
s.push(x:"200");
s.print();
System.out.println("Size=" +s.size());
}
}
Why doesn't this work?
Why does it say invalid statement while creating the StackSimple object? The problem is in the main class while running it. There are errors while pushing the elements.
Error while compiling
When passing parameters to a function you just pass the values.
In your case not StackSimple(capacity:3) but just StackSimple(3)
First question, which version of Java are you using.
Second, in Java you should be passing as a variable instead of StackSimple(capacity:3). Change your main method to below, here is my recommendation:
StackSimple s = new StackSimple(3);
s.push("books");
s.push("something");
s.push("200");
s.print();
System.out.println("Size=" +s.size());
You are not at all pushing the value in the stack, your pusch function is not working as it is expected to work.
Here is the correct program.
class StackSimple {
private long capacity = 1000;// maximum size of array
private int idx_top;
private Object data[];
public StackSimple(int capacity) {
idx_top = -1;
this.capacity = capacity;
data = new Object[capacity];
}
public boolean isEmpty() {
return (idx_top < 0);
}
public boolean isFull() {
return (idx_top >= capacity - 1);
}
public int size() {
return idx_top + 1;
}
public boolean push(Object x) {
if (isFull()) {
throw new IllegalArgumentException("ERROR:Stack Overflow.Full Stack");
} else {
data[++idx_top] = x;
return true;
}
}
public Object pop() {
if (isEmpty())
throw new IllegalArgumentException("ERROR:Stack Underflow.Empty Stack.");
else {
return data[idx_top--];
}
}
public Object top() {
if (isEmpty())
throw new IllegalArgumentException("ERROR:Stack Underflow.Empty Stack.");
else {
return data[idx_top];
}
}
public void print() {
for (int i = size() - 1; i >= 0; i--)
System.out.println(data[i]);
}
}
public class test {
public static void main(String[] args) {
StackSimple s = new StackSimple(3);// error shows here
s.push("books");
s.push("something");
s.push("200");
s.print();
System.out.println("Size=" + s.size());
}
}
I need to loop through the stack until it is empty, adding each element to the queue. Then do the opposite. Loop through the queue until it is empty, adding each element back onto the stack
public class Q1 {
public static void reverseStack(Stack st){
}
}
Here is my test:
public class Q1Test {
#Test
public void testQ1() {
Stack st = new Stack(5);
st.push("A");
st.push("B");
Q1.reverseStack(st);
assertEquals("A",(String) st.top());
}
}
I have been trying to do the Q1 code and never get it to succeed and always end up fail. Can anyone implement a methods as said above to make the Q1 test succeed please?
Here is a working example:
Q1.java
import java.util.ArrayList;
import java.util.List;
public class Q1 {
private List<String> list;
public Q1() {
list = new ArrayList<String>();
}
public String pop_front() {
if (!list.isEmpty()) {
String front = list.get(0);
for (int i = 0; i < list.size()-1; i++) {
list.set(i, list.get(i+1));
}
list.remove(list.size()-1);
return front;
} else {
return null;
}
}
public void push_back(String obj) {
list.add(obj);
}
public String front() {
if (!list.isEmpty()) {
return list.get(0);
} else {
return null;
}
}
public boolean isEmpty() {
return list.isEmpty();
}
public static void reverseStack(Stack stack) {
Q1 queue = new Q1();
while (!stack.isEmpty()) {
queue.push_back(stack.pop());
}
while (!queue.isEmpty()) {
stack.push(queue.pop_front());
}
}
}
A Stack class:
Stack.java
package com.dub;
import java.util.ArrayList;
import java.util.List;
public class Stack {
private List<String> list;
public Stack() {
list = new ArrayList<String>();
}
public String pop() {
if (!list.isEmpty()) {
String top = list.get(list.size()-1);
list.remove(list.size()-1);
return top;
} else {
return null;
}
}
public void push(String obj) {
list.add(obj);
}
public String top() {
if (!list.isEmpty()) {
return list.get(list.size()-1);
} else {
return null;
}
}
public boolean isEmpty() {
return list.isEmpty();
}
}
and now the test method:
public static void main(String[] args) {
Stack stack = new Stack();
stack.push("A");
stack.push("B");
stack.push("C");
System.out.println("top: " + stack.top());
Q1.reverseStack(stack);
System.out.println("top: " + stack.top());
}
It prints as expected:
top: C
top: A
Link Class:
class Link
{
public int data;
public Link next;
public Link previous;
public int count;
public Link(int x, int y)
{
data=x;
count = y;
}
public void displayLink()
{
System.out.print(data+" ");
}
}
DoublyLinkList class (in quicksort class having some errors or could any one change quick sort method without using indexes):
class DoublyLinkList
{
private Link first;
private Link last;
public DoublyLinkList()
{
first=null;
last=null;
}
public void insert(int x,int y)
{
Link newLink=new Link(x,y);
newLink.next=null;
if(isEmpty())
{
first=newLink;
}
else
{
last.next=newLink;
newLink.previous=last;
}
last=newLink;
}
public boolean isEmpty()
{
return(first==null);
}
public void displayList()
{
Link current=first;
while(current!=null)
{
current.displayLink();
current=current.next;
}
}
public void quicksort()
{
Link pivot = first;
Link too_big_index = first.next;
int temp;
Link too_small_index = last;
while (too_big_index.data <= pivot.data)
too_big_index =too_big_index.next;
while (too_small_index.data > pivot.data)
too_small_index=too_small_index.previous;
if(too_big_index.count < too_small_index.count)
{
temp = too_big_index.data;
too_big_index.data =too_small_index.data;
too_small_index.data=temp;
// swap data[too_big_index] and data[too_small_index]
}
while (too_small_index.count > too_big_index.count)
{
quicksort();
}
temp = too_small_index.data;
too_small_index.data =pivot.data;
pivot.data=temp;
}
}
Main Class (First display method is showing numbers but the other one is not working. Don't know why. I think quicksort class is not working, need help to improve it.)
public class Test
{
public static void main(String args[])
{
DoublyLinkList d = new DoublyLinkList();
d.insert(34,0);
d.insert(75,1);
d.insert(86,2);
d.insert(39,3);
d.insert(10,4);
d.insert(61,5);
d.insert(22,6);
d.insert(3,7);
d.insert(1,8);
d.insert(125,9);
d.insert(162,10);
d.displayList();
d.quicksort();
d.displayList();
}
}
I am implementing an immutable queue using the following code :
import java.util.NoSuchElementException;
import java.util.Queue;
public class ImmutableQueue<E> {
//Two stacks are used. One is to add items to the queue(enqueue) and
//other is to remove them(dequeue)
E returnedItem;
private ImmutableQueue(ReversableStack<E> order, ReversableStack<E> reverse) {
this.order = order;
this.reverse = reverse;
}
//initially both stacks are empty
public ImmutableQueue() {
this.order = ReversableStack.emptyStack();
this.reverse = ReversableStack.emptyStack();
}
public ImmutableQueue<E> enqueue(E e) {
if (null == e)
throw new IllegalArgumentException();
return new ImmutableQueue<E>(this.order.push(e), this.reverse);
}
public ImmutableQueue<E> dequeue() {
if (this.isEmpty())
throw new NoSuchElementException();
if (!this.reverse.isEmpty()) {
returnedItem = this.reverse.head;
return new ImmutableQueue<E>(this.order, this.reverse.tail);
} else {
returnedItem = this.reverse.head;
return new ImmutableQueue<E>(ReversableStack.emptyStack(),
this.order.getReverseStack().tail);
}
}
private static class ReversableStack<E> {
private E head; //top of original stack
private ReversableStack<E> tail; //top of reversed stack
private int size;
//initializing stack parameters
private ReversableStack(E obj, ReversableStack<E> tail) {
this.head = obj;
this.tail = tail;
this.size = tail.size + 1;
}
//returns a new empty stack
public static ReversableStack emptyStack() {
return new ReversableStack();
}
private ReversableStack() {
this.head = null;
this.tail = null;
this.size = 0;
}
//Reverses the original stack
public ReversableStack<E> getReverseStack() {
ReversableStack<E> stack = new ReversableStack<E>();
ReversableStack<E> tail = this;
while (!tail.isEmpty()) {
stack = stack.push(tail.head);
tail = tail.tail;
}
return stack;
}
public boolean isEmpty() {
return this.size == 0;
}
public ReversableStack<E> push(E obj) {
return new ReversableStack<E>(obj, this);
}
}
private ReversableStack<E> order;
private ReversableStack<E> reverse;
private void normaliseQueue() {
this.reverse = this.order.getReverseStack();
this.order = ReversableStack.emptyStack();
}
public E peek() {
if (this.isEmpty())
throw new NoSuchElementException();
if (this.reverse.isEmpty())
normaliseQueue();
return this.reverse.head;
}
public boolean isEmpty() {
return size() == 0;
}
//returns the number of items currently in the queue
public int size() {
return this.order.size + this.reverse.size;
}
public static void main(String[] args)
{
ImmutableQueue<Integer> newQueue = new ImmutableQueue<Integer>();
newQueue=newQueue.enqueue(5);
newQueue=newQueue.enqueue(10);
newQueue=newQueue.enqueue(15);
//newQueue = newQueue.dequeue();
//System.out.print(newQueue);
int x = newQueue.peek();
//ImmutableQueue<Integer> x = newQueue.dequeue();
System.out.println(x);
}
}
The dequeue function does not seem to return the removed item, it only removes it. This the commented line by the way. How do I access the removed item ?
I have created a variable of type E in the main class. Now how do I access it in main and get the dequed value ?
Thanks
My java class comps up with a NullPointerException.Please help!
The error messages:
java.lang.NullPointerException at
RandomizedQueue.dequeue(52 line) at
RandomizedQueue$IndependantIterator.next (88 line) at
RandomizedQueue.main (104)
I have signed the line number in the end of the error code line.
import java.util.Iterator;
public class RandomizedQueue<Item> implements Iterable<Item> {
private int number=0;
private Node first=null;
private Node end=null;
private class Node {
Item item;
Node next=null;
Node last=null;
}
private Node Random() {
double r = Math.random();
int n = (int) (r*number);
if(n==0) n=1;
Node ob=first;
for(int i=0;i<(n-1);i++) {
ob = ob.next;
}
return ob;
}
public RandomizedQueue() {
Node empty=new Node();
}
public boolean isEmpty() {
return number==0;
}
public int size() {
return number;
}
public void enqueue(Item item) {
if(item==null) throw new NullPointerException();
number++;
if(first==null) {
first = new Node();
end = first;
first.item = item;
}
else {
Node oldfirst = first;
first = new Node();
first.item = item;
first.next = oldfirst;
oldfirst.last = first;
}
}
public Item dequeue() {
Node ob=Random();
Item back=ob.item;
if(ob==end) {
end = ob.last;
ob.last.next=null; //52 line
}else if(ob==first) {
first=first.next;
first.last=null;
}
else {
ob.last.next=ob.next;
ob.next.last=ob.last;
}
return back;
}
public Node sample() {
return Random();
}
public Iterator<Item> iterator() {
return new IndepentRandomIterator();
}
private class IndepentRandomIterator implements Iterator<Item> {
private RandomizedQueue<Item> iq = new RandomizedQueue<Item>();
Node scan = first;
public IndepentRandomIterator() {
while(scan != null) {
iq.enqueue(scan.item);
scan=scan.next;
}
}
public boolean hasNext() {
return iq.number >0;
}
public void remove() {
throw new UnsupportedOperationException();
}
public Item next() {
if(iq.number==0) throw new java.util.NoSuchElementException();
return iq.dequeue(); //88
}
}
public static void main(String[] args) {
RandomizedQueue<String> test = new RandomizedQueue<String>();
test.enqueue("Luo");
test.enqueue("Jiebin");
test.enqueue("is");
test.enqueue("genious");
test.dequeue();
test.dequeue();
StdOut.println("Is it empty?"+test.isEmpty());
StdOut.println("Size: "+test.size());
StdOut.println("A sample: "+test.sample());
Iterator<String> it = test.iterator();
while(it.hasNext()) {
String s = it.next(); //104
}
}
}
It's because ob.last is null. The only time that end is set is when item is first in enqueue(). And last is never set there. In dequeue(), it goes to the if block if ob == end. Since end.last == null, therefore ob.last == null too and ob.last.next will throw NPE.