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
Related
i implemented a Stack Class.
Now, i want to create a Queue based on that stack. Like this :
public class Queue<E> {
private Stack<E> next;
private Stack<E> next2;
public E first() {
}
public Queue<E> enqueue(E e) {
}
public Queue<E> dequeue() {
}
public boolean isEmpty() {
if (this.next == null) {
return true;
}
if (Stack.isEmpty(next)) {
return true;
}
return false;
}
}
I don't know where to start. How can i solve this problem? My first ideas was to use the method "reverse" in Stack. But i'm not sure.
There are 2 ways to do this. First one is to push at the end of stack using your function reverse. Like this
public class Queue<E> {
private Stack<E> next;
public E front() {
return (E) Stack.<E>top(next);
}
public Queue<E> enqueue(E e) {
Stack<E> nextNew = Stack.reverse(next);
nextNew = Stack.push(nextNew, e);
nextNew = Stack.reverse(nextNew);
Queue<E> q = new Queue<E>();
q.next = nextNew;
return q;
}
public Queue<E> dequeue() {
Stack<E> nextNew = Stack.pop(next);
Queue<E> q = new Queue<E>();
q.next = nextNew;
return q;
}
public boolean isEmpty() {
if (this.next == null) {
return true;
}
if (Stack.isEmpty(next)) {
return true;
}
return false;
}
}
I think it's slickest with recursion:
public class Queue<E> {
private Stack<E> stack;
public Queue(Stack stack) {
this.stack = stack;
}
public E front() {
return Stack.top(stack);
}
public Queue<E> enqueue(E newValue) {
if (Stack.top(stack) == null) {
return new Queue(Stack.push(Stack.create(), newValue));
}
return new Queue<>(Stack.push(new Queue(Stack.pop(stack)).enqueue(newValue).stack, Stack.top(stack)));
}
public Queue<E> dequeue() {
return new Queue<>(Stack.pop(stack));
}
public String toString() {
return "Q: " + stack.toString();
}
}
Note that there's no reversing required.
I thought some of the code in the Stack class was a little unclear with the "a" parameters and extra variables, so I refactored it a bit and stripped out everything that wasn't used. I also added a toString() which traverses the stack recursively:
public class Stack<E> {
private final E value;
private final Stack<E> next;
private Stack(E value, Stack<E> next) {
this.value = value;
this.next = next;
}
public static <E> Stack<E> create() {
return new Stack<>(null, null);
}
public static <E> Stack<E> push(Stack<E> stack, E newValue) {
return new Stack<E>(newValue, stack);
}
public static <E> Stack<E> pop(Stack<E> stack) {
if (stack == null) {
return new Stack<E>(null, null);
} else if (stack.value == null) {
return new Stack<>(null, null);
} else if (stack.next == null) {
return new Stack<E>(null, null);
} else {
return stack.next;
}
}
public static <E> E top(Stack<E> stack) {
if (stack == null) {
return null;
} else if (stack.value == null) {
return null;
} else {
return stack.value;
}
}
public String toString() {
if (Stack.top(next) == null) {
return (value != null ? value.toString() : "Null");
}
return (value != null ? value.toString() : "Null") + " " + next.toString();
}
}
And a little testing class. To show the difference between the stack and the queue, it loads up a stack first, then passes it to a Queue and adds a few more elements, then pulls a few off the front:
public class QueueWithStackMain {
public static void main(String[] args) {
Stack<String> stack = Stack.create();
stack = Stack.push(stack, "1");
System.out.println(stack.toString());
stack = Stack.push(stack, "2");
System.out.println(stack.toString());
stack = Stack.push(stack, "3");
System.out.println(stack.toString());
Queue<String> queue = new Queue<>(stack);
System.out.println(queue.toString());
queue = queue.enqueue("4");
System.out.println(queue.toString());
queue = queue.enqueue("5");
System.out.println(queue.toString() + " -> " + queue.front());
queue = queue.dequeue();
System.out.println(queue.toString() + " -> " + queue.front());
}
}
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 am experimenting with lock free linked lists. This is my first shot but I have no idea why the toString method always returns an empty string even if I can see values in the debugger.
package com.linkedq;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicReference;
public class LinkedQueue <E> {
private static class Node <E> {
final E item;
final AtomicReference<Node<E>> next;
Node(E item, Node<E> next) {
this.item = item;
this.next = new AtomicReference<>(next);
}
#Override
public String toString() {
return item.toString();
}
}
private AtomicReference<Node<E>> head = new AtomicReference<>(new Node<E>(null, null));
private AtomicReference<Node<E>> tail = head;
public boolean put(E item) {
Node<E> newNode = new Node<E>(item, null);
while (true) {
Node<E> curTail = tail.get();
Node<E> residue = curTail.next.get();
if (curTail == tail.get()) {
if (residue == null) /* A */ {
if (curTail.next.compareAndSet(null, newNode)) /* C */ {
tail.compareAndSet(curTail, newNode) /* D */ ;
return true;
}
} else {
tail.compareAndSet(curTail, residue) /* B */;
}
}
}
}
public void remove(E item) {
Node<E> current = this.head.get().next.get();
Node<E> next = null;
while (current != null) {
next = current.next.get();
if (next.equals(item)) {
if (!current.next.compareAndSet(next, next.next.get())) {
// some other thread changed the list, do a retry
remove(item);
}
}
current = next;
}
}
#Override
public String toString() {
Node<E> current = head.get().next.get();
StringBuilder sb = new StringBuilder();
while (current != null) {
sb.append(current).append(", ");
current = current.next.get();
}
return sb.toString();
}
public static void main(String[] args) throws InterruptedException {
final ExecutorService es = Executors.newFixedThreadPool(10);
final LinkedQueue<Integer> q = new LinkedQueue<>();
for (int i=0; i<10000; i++) {
es.execute(new Inserter(q, i));
}
// es.shutdown();
// es.awaitTermination(1L, TimeUnit.HOURS);
System.out.println("FIN" + q);
}
private static class Inserter implements Runnable {
private final LinkedQueue<Integer> q;
private final int value;
public Inserter(LinkedQueue<Integer> q, int value) {
this.q = q;
this.value = value;
}
#Override
public void run() {
q.put(value);
System.out.println("q = " + q);
}
}
}
At least one obvious error is that your head and tail are actually the same AtomicReference object, so when you update the tail, the head is updated as well. Use
private AtomicReference<Node<E>> head = new AtomicReference<>(new Node<E>(null, null));
private AtomicReference<Node<E>> tail = new AtomicReference<>(head.get());
Another obvious mistmatch is that the first element you add inside the tail and the head:
tail.compareAndSet(curTail, newNode) ;
While when you read, you start printing from the next of the head:
Node<E> current = head.get().next.get();
So even without having multiple threads, etc, just adding one element and printing the list does not work. Add unit tests to verify the behavior!
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.
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());
}
}
}