addFirst() in java.util.LinkedList - java

This is for homework.
I am making a stack using a linked list. I have chosen to use the linked list from Java's java.util.LinkedList package. When I call the addFirst() method in my Main class, the program won't finish. It acts like an infinite loop, but as far as I know there are no loops involved. Here is the code:
package assignment3;
import java.util.LinkedList;
/**
*
* #author Eric
*/
public class LinkedListStack<T> {
LinkedList linkedList = new LinkedList();
public boolean isEmpty() {
if (linkedList.isEmpty()) {
return true;
} else {
return false;
}
}
public int size() {
int size = linkedList.size();
System.out.println("The size of the stack is " + size);
return size;
}
// This is the problem method.
public void push(T element) {
linkedList.addFirst(element);
}
public void pop() {
while(!linkedList.isEmpty()){
linkedList.removeFirst();
}
}
public void peek() {
while(!linkedList.isEmpty()){
linkedList.peek();
}
System.out.println("The first element in the stack is " + linkedList.peek());
}
}
This is the class Main that calls the push() method.
package assignment3;
/**
*
* #author Eric
*/
public class Main {
public static void main(String args[]) {
LinkedListStack linkedListStack = new LinkedListStack();
linkedListStack.push(1); // This never finishes.
linkedListStack.peek();
linkedListStack.size();
}
}
It's very hard to test LinkedListStack.java because I cannot push anything onto the stack. I have no idea what's wrong.

while(!linkedList.isEmpty()){
linkedList.peek();
}
peek() will never change a linked list from nonempty to empty, since it doesn't change the list.
but as far as I know there are no loops involved
What do you think while is?

Related

cs 61b project1b Cannot resolve method get in Deque

I wrote these codes in Idea. The IDE throws "can't resolve method get in Deque.java" when I finished Palindrome.java. How come? I actually did that in the Deque.java. Although in the LinkedListDeque inherited the get() method from the origin LinkList.
I found another solution by changing
Deque stringDeque = wordToDeque(word);
to
LinkListDeque stringDeque = (LinkListDeque) wordToDeque(word);
But I am still curious about how cannot find get in Deque.
class diagram here
Deque interface
/** Create an interface in a new file named Deque.
* java that contains all of the methods that appear in both ArrayDeque and LinkedListDeque.
* #param <Item>
*/
public interface Deque<Item> {
int size = 0;
/** Adds an item of type T to the front of the deque. */
void addFirst(Item item);
/** Adds an item of type T to the back of the deque. */
void addLast(Item item);
/** Returns true if deque is empty, false otherwise. */
default boolean isEmpty() {
return size == 0;
};
/** Prints the items in the deque from first to last,
* separated by a space. Once all the items have been printed, print out a new line. */
void printDeque();
/** Removes and returns the item at the front of the deque. If no such item exists, returns null. */
Item removeFirst();
/** Removes and returns the item at the back of the deque. If no such item exists, returns null. */
Item removeLast();
/** Gets the item at the given index, where 0 is the front, 1 is the next item, and so forth.
* If no such item exists, returns null. Must not alter the deque! */
Item get(int index);
}
class LinkedLinkDeque.java
import java.util.LinkedList;
import java.util.NoSuchElementException;
/**
* Isn't this solution kinda... cheating? Yes.
*/
public class LinkedListDeque<Item> extends LinkedList<Item> implements Deque<Item> {
#Override
public void printDeque() {
System.out.println("dummy");
}
public Item getRecursive(int i) {
return get(i);
}
#Override
public Item removeFirst() {
try {
return super.removeFirst();
} catch (NoSuchElementException e) {
return null;
}
}
#Override
public Item removeLast() {
try {
return super.removeLast();
} catch (NoSuchElementException e) {
return null;
}
}
}
Palindrome.java
import java.util.Deque;
import java.util.LinkedList;
public class Palindrome {
/** Given a String, wordToDeque should return a Deque
* where the characters appear in the same order as in the String.
* #param word
*/
public Deque<Character> wordToDeque(String word) {
Deque<Character> stringDeque = new LinkedListDeque<>();
for (String s : word.split("")) {
stringDeque.addLast(s.charAt(0));
}
return stringDeque;
}
/** Return true if the given word is a palindrome, and false otherwise. */
public boolean isPalindrome(String word) {
if (word.length() == 0 || word.length() == 1) {
return true;
}
Deque stringDeque = wordToDeque(word);
int index = word.length() / 2;
for (int i = 0; i < index; i += 1) {
if (stringDeque.get(i) != stringDeque.get(word.length() - i - 1)) { return false; }
}
return true;
}
}
You have your own Deque interface but you are also working with the java.util.Deque interface. This can result in problems as the interface Deque is defined twice in different namespaces. Specially in your Palindrome.java file you are using the java.util.Deque interface because of the import java.util.Deque line at the top and NOT your Deque interface as you might expect.
Because of that you get the error message that the get(int) method is missing. That is correct, the java.util.Deque method does not define a get(int) method (but the java.util.List interface does).
Do not name classes with names which already exists in java. As you see that can result in naming conflict/issues.

Stack and Array List

My assignment is to write a test program that prompts a user for 5 strings and displays them in reverse order using MyStack and ArrayList. I need help figuring out how to take user input and put it into the stack and print it in reverse.
MyStack Class
MyMain
My Main:
package arraylist;
import java.util.Scanner;
/**
*
* #author dghelardini
*/
public class ArrayList {
/**
* #param args the command line arguments
*/
public static void main(String[] args)
{
Scanner userIn = new Scanner(System.in);
System.out.print("Enter five names: ");
}
}
MyStack Class:
package arraylist;
/**
*
* #author dghelardini
*/
public class MyStack extends ArrayList
{
private ArrayList<Object> theList = new ArrayList<>();
public boolean isEmpty()
{
return theList.isEmpty();
}
public int getSize()
{
return theList.size();
}
public Object peek()
{
return theList.get(getSize()-1);
}
public Object pop()
{
Object o = theList.get(getSize()-1);
theList.remove(getSize()-1);
return o;
}
public void push(Object o)
{
theList.add(o);
}
#Override
public String toString()
{
return "stack:" + theList.toString();
}
}
Scanner:
http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html?is-external=true
The user enters the string, then you call the stack to store the 5 strings. Then when you pop, the stack returns the last item that

LinkedListStack System.out.println

Im working on a LinkedListStack and have to print out for example "size".
here is my LinkedListStack:
public class LinkedListStack {
private class Element {
public Object value;
public Element next;
}
private Element top;
private int size=0;
public void push(Object o) {
Element e=new Element();
e.value=o;
e.next=top;
top=e;
size++;
}
public Object pop() {
if (top!=null) {
Object v=top.value;
top=top.next;
size--;
return v;
} else {
return null;
}
}
public boolean isEmpty(){
return top==null;
}
public int size() {
return size;
}
public Object get(int n) {
Element current=top;
int i=0;
while (i<n && current!=null) {
current=current.next;
i++;
}
if (current==null)
return null;
else
return current.value;
}
}
I know I have to use
System.out.println ("...");
and that i need a new class, let's call it Stacki. Is must contain a main method where i can use the methods and print them out. So that would be:
public class Stacki {
public static void main(String[] args) {
}
}
how do I put
public void size() {
System.out.println ("size is"+size());
}
in that class? Because i cannot use the block as such, an error occurs.
Thank you :)
You instantiate your other class within Stacki, like:
public class Stacki {
public static void main(String[]) {
LinkedListStack stack = new LinkedListStack();
System.out.println("size is: " + stack.size());
... then you probably add some elements, remove some, and whenever you want to:
System.out.println("size is: " + stack.size());
And hint: Stacki is a rather nothing-saying name. Better call that class LinkedListStackTester or something alike. Names always say what the thing they denote is about!
And finally: this is really basic stuff. It doesn't make much sense to create your own stack class, when you have no idea how to put that to use. In that sense: you probably want to spend some hours here and work yourself through those tutorials!

Homework StackoverflowError

I'm doing some school exercises about implementing interfaces and I've already got the workspace and Test classes provided for me. What I have to do is basically implement the methods, run the Test Classes, and make sure they pass the tests.
Here is my code: http://pastebin.com/e8Vh3snC
package queue;
import java.util.*;
public class FifoQueue<E> extends AbstractQueue<E> implements Queue<E> {
private QueueNode<E> last;
private int size=0;
private FifoQueue<E> queue;
public FifoQueue() {
queue = new FifoQueue<E>();
}
/**
* Returns an iterator over the elements in this queue
* #return an iterator over the elements in this queue
*/
public Iterator<E> iterator() {
return queue.iterator();
}
/**
* Returns the number of elements in this queue
* #return the number of elements in this queue
*/
public int size() {
return size;
}
/**
* Inserts the specified element into this queue, if possible
* post: The specified element is added to the rear of this queue
* #param x the element to insert
* #return true if it was possible to add the element
* to this queue, else false
*/
public boolean offer(E x) {
if(queue.add(x)){
size++;
return true;
} else {
return false;
}
}
/**
* Retrieves and removes the head of this queue,
* or null if this queue is empty.
* post: the head of the queue is removed if it was not empty
* #return the head of this queue, or null if the queue is empty
*/
public E poll() {
if(queue.size() > 0) {
size=size-1;
}
return queue.poll();
}
/**
* Retrieves, but does not remove, the head of this queue,
* returning null if this queue is empty
* #return the head element of this queue, or null
* if this queue is empty
*/
public E peek() {
return queue.peek();
}
private static class QueueNode<E> {
E element;
QueueNode<E> next;
private QueueNode(E x) {
element = x;
next = null;
}
}
}
Here are the Test Classes, in case you want to see them (provided by the school, so I doubt they're incorrect): http://pastebin.com/uV46j0rm
package testqueue;
import static org.junit.Assert.*;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.util.NoSuchElementException;
import java.util.Iterator;
import queue.FifoQueue;
public class TestFifoQueue {
private FifoQueue<Integer> myIntQueue;
private FifoQueue<String> myStringQueue;
#Before
public void setUp() throws Exception {
myIntQueue = new FifoQueue<Integer>();
myStringQueue = new FifoQueue<String>();
}
#After
public void tearDown() throws Exception {
myIntQueue = null;
myStringQueue = null;
}
/**
* Test if a newly created queue is empty.
*/
#Test
public final void testNewFifoQueue() {
assertTrue(myIntQueue.isEmpty());
assertTrue(myIntQueue.size() == 0);
}
/** Test a single offer followed by a single peek. */
#Test
public final void testPeek() {
myIntQueue.offer(1);
int i = myIntQueue.peek();
assertEquals("peek on queue of size 1", 1, i);
assertTrue(myIntQueue.size() == 1);
}
/**
* Test a single offer followed by a single poll.
*/
#Test
public final void testPoll() {
myIntQueue.offer(1);
int i = myIntQueue.poll();
assertEquals("poll on queue of size 1", 1, i);
assertTrue("Wrong size after poll", myIntQueue.size() == 0);
}
/**
* Test peek of empty queue.
*/
#Test
public final void testPeekOfEmpty() {
assertEquals("Front of empty queue not null", null, myIntQueue.peek());
}
/**
* Test poll of empty queue.
*/
#Test
public final void testPollOfEmpty() {
assertEquals("Poll of empty queue should return null", null, myIntQueue
.poll());
}
/**
* Test that implementation works for a queue of strings.
*/
#Test
public final void testStringQueue() {
myStringQueue.offer("First");
myStringQueue.offer("Second");
myStringQueue.offer("Third");
assertTrue("Wrong size of queue", myStringQueue.size() == 3);
assertEquals("peek on queue of strings", "First", myStringQueue.peek());
assertEquals("String First expected", "First", myStringQueue.poll());
assertEquals("String Second expected", "Second", myStringQueue.poll());
assertEquals("String Third expected", "Third", myStringQueue.poll());
assertTrue("Queue of strings should be empty", myStringQueue.isEmpty());
}
/**
* Test that polling gives elements in right order.
*/
#Test
public final void testOrder() {
myIntQueue.offer(1);
myIntQueue.offer(2);
myIntQueue.offer(3);
myIntQueue.offer(4);
myIntQueue.offer(5);
for (int i = 1; i <= 5; i++) {
int k = myIntQueue.poll();
assertEquals("poll returns incorrect element", i, k);
}
assertTrue("Queue not empty", myIntQueue.isEmpty());
}
/**
* Test that polling all elements gives an empty queue.
*/
#Test
public final void testMakeQueueEmpty() {
myIntQueue.offer(1);
myIntQueue.offer(2);
myIntQueue.poll();
myIntQueue.poll();
assertTrue("Wrong size after poll", myIntQueue.size() == 0);
assertTrue("Queue not empty after poll", myIntQueue.isEmpty());
myIntQueue.offer(3);
myIntQueue.offer(4);
assertTrue("Wrong size after offer", myIntQueue.size() == 2);
for (int i = 3; i <= 4; i++) {
int k = myIntQueue.poll();
assertEquals("poll returns incorrect element", i, k);
}
assertTrue("Wrong size after poll", myIntQueue.size() == 0);
assertTrue("Queue not empty after poll", myIntQueue.isEmpty());
}
}
So when I try to run the tests, I get multiple StackOverflowErrors at queue.FifiQueue.(FifoQueue.java:10)
I've been looking through the code for some hours now but can't figure out where I've written bad code.
PS: I know some of the methods are implemented incorrectly (I will try to fix them later) but as for now I'm just trying to pass the offer() och size() methods.
Your constructor is calling itself, causing infinite recursion:
public FifoQueue() {
queue = new FifoQueue<E>();
}
Maybe you mean to wrap some other type of queue or list internally?

Return an iterator

Searching for info about the iterator, I found only examples that showed how to iterate over a collection, and not returning the Iterator, like I want to do.
I am practicing for the exam, so I'm trying out some programming excercises to prepare myself, and this one is about the iterator pattern.
I want to implement the getKnightPositionIterator, . You can see the code below. This code is not mine, I found this.
package iterator;
import java.util.*;
public class Position {
/** return an iterator that will return all positions
* that a knight may reach from a given starting position.
*/
public static Iterator<Position> getKnightPositionIterator(Position p) {
return null;
}
/** create a position.
* #param r the row
* #param c the column
*/
public Position(int r, int c) {
this.r = r; this.c = c;
}
protected int r;
protected int c;
/** get the row represented by this position.
* #return the row.
*/
public int getRow() { return r; }
/** get the column represented by this position.
* #return the column.
*/
public int getColumn() { return c; }
public boolean equals(Object o) {
if (o.getClass() != Position.class) { return false; }
Position other = (Position) o;
return r==other.r && c==other.c;
}
public int hashCode() {
// works ok for positions up to columns == 479
return 479*r+c;
}
public String toString() {
return "["+r+","+c+"]";
}
}
How ever, I figure that I have to create an Iterator to return, so, so far, this is my attemp.
public static Iterator<Position> getKnightPositionIterator(Position p) {
Iterator<Position> knightPosIter = Position.getKnightPositionIterator(p);
for(Iterator<Position> positions = knightPosIter; positions.hasNext(); ) {
//What should I write here?
}
return knightPosIter;
}
First, make your class implement Iterable interface
public class Position implements Iterable<Position>
and write the public Iterator<Positions> iterator(); method as outlined below instead of providing a static method in your example.
As you actually need to compute a collection of reachable positions in one way or another, you will need a structure to hold it. Any such structure will normally be iterable and, thus, will have an iterator method. So a lazy implementation could look like this:
#Override
public Iterator<Position> iterator()
{
// make sure this returns e.g. Collections.unmodifiableList
Collection<Position> positions = computeReachablePositions();
return positions.iterator();
}
In case you have some other structure to compute and store your positions that is not iterable (not advisable), implement an iterator from scratch as follows (an array of positions assumed):
#Override
public Iterator<Position> iterator()
{
// must be final to be accessible from the iterator below
final Position[] positions = computeReachablePositions();
return new Iterator<Position>() {
int index = 0;
#Override
public boolean hasNext()
{
return index < positions.length;
}
#Override
public Position next()
{
if (hasNext())
{
Position value = positions[index];
index++;
return value;
}
throw new NoSuchElementException("No more positions available");
}
#Override
public void remove()
{
throw new UnsupportedOperationException("Removals are not supported");
}};
}

Categories

Resources