I am attempting to create a custom Iterator on a LinkedList class I have made. I have been asked to alter the add function so that it adds objects Term in order from smallest to largest. (Term is a simple class taking the form Term(int power))
I cannot figure out how to create a loop in addTerm() in order to keep searching the next element to see if it is larger than the current power in Term. Can anyone help?
import java.util.Iterator;
public class customImpl implements custom{
private static class Node {
Term data;
Node next;
}
private Node head;
private class TermIterator implements Iterator<Term> {
private Node current;
private TermIterator(Node start) {
current = start;
}
#Override
public boolean hasNext() {
return current != null;
}
#Override
public Term next() {
Term result = current.data;
current = current.next;
return result;
}
#Override
public void remove() {
throw new UnsupportedOperationException("Not supported");
}
}
/**
* Add a term to the expression
*
* #param term the term to be added.
*/
#Override
public void addTerm(Term term) {
TermIterator iterator = new TermIterator(head);
Node newNode = new Node();
while(iterator.hasNext()) {
if(term.getPower() > iterator.next().getPower()) {
newNode.next = head;
}
else newNode.data = term;
}
newNode.data = term;
newNode.next = head;
head = newNode;
}
/**
* Returns an iterator over elements of type {#code T}.
*
* #return an Iterator.
*/
#Override
public Iterator<Term> iterator() {
return new TermIterator(head);
}
}
You cannot easily use your iterator as it goes through values instead of nodes:
#Override
public void addTerm(Term term) {
Node newNode = new Node();
newNode.term = term;
Node smaller = null; //smaller holds last element smaller than new term
Node current = head;
while(current != null) {
if(term.getPower() > current.term.getPower()) {
smaller = current;
break;
}
current = current.next;
}
if (smaller == null) {
newNode.next = head;
head = newNode;
} else {
newNode.next = smaller.next;
smaller.next = newNode;
}
}
If you want to use iterator, than you should define the 'Node' iterator (and use it in your addTerm method), and re-use it to define the 'Term' iteraotr:
class NodeIterator implements Iterator<Node> {
Node next;
NodeIterator() {
next = head;
}
#Override
public boolean hasNext() {
return (next != null);
}
#Override
public Node next() {
if (next == null) throw new NoSuchElementException();
Node res = next;
next = next.next;
return res;
}
#Override
public void remove() {
throw new UnsupportedOperationException("Not supported yet.");
}
}
class TermIterator implements Iterator<Term> {
final NodeIterator iter = new NodeIterator();
#Override
public boolean hasNext() {
return iter.hasNext();
}
#Override
public Term next() {
return iter.next().term;
}
#Override
public void remove() {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
}
Related
I'm making my own linkedlist class for an exercise I'm doing, and I'm unsure about the next() function I'm using works as I intend. The way I want it to work is for it to start from the first node in the list and then follow links to the following nodes until it reaches the last node in the list.
private class MyIterator implements java.util.Iterator<MyNode<E>> {
private MyNode<E> current = firstNode;
private int acceptableModCnt = modCount;
#Override
public boolean hasNext() {
return current.next != null;
}
#Override
public MyNode<E> next() {
if (modCnt != acceptableModCnt) {
throw new java.util.ConcurrentModificationException( );
}
if (!hasNext()) {
throw new java.util.NoSuchElementException( );
}
MyNode<E> nextNode = current.next;
current = current.next;
return nextNode;
}
}
Have I implemented the next() function correctly?
I am trying to print the first and last elements in a deque using a toString method however I'm not entirely sure if I am overwriting the toString method correctly.
As far as I can tell, the methods all seem to behave correctly but I have no way of being able to tell as I am unable to see any readable output.
I am aware that there is already a deque interface, however this is part of an exercise in using generics in Java.
This piece of code should create a deque, be able to add values to the front of the deque, remove values from the front, add values to the rear and remove values from the rear.
Here's the class in question:
import java.util.Iterator;
import java.util.NoSuchElementException;
class Deque<T> implements Iterable<T> {
private class Node<T> {
public Node<T> left, right;
private final T item;
public Node(T item) {
if (item == null) {
throw new NullPointerException();
}
this.item = item;
}
public void connectRight(Node<T> other) {
this.right = other;
other.left = this;
}
}
private class DequeIterator implements Iterator<T> {
private Node<T> curr = head;
public boolean hasNext() {
return curr != null;
}
public void remove() {
throw new UnsupportedOperationException();
}
public T next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
T item = curr.item;
curr = curr.right;
return item;
}
}
private Node<T> head, tail;
private int size;
public Iterator<T> iterator() {
return new DequeIterator();
}
public Deque() {
}
public int size() {
return size;
}
public boolean isEmpty() {
return size() == 0;
}
public void checkInvariants() {
assert size >= 0;
assert size > 0 || (head == null && tail == null);
assert (head == null && tail == null) || (head != null && tail != null);
}
public void addFirst(T item) {
Node<T> prevHead = head;
Node<T> newHead = new Node<T>(item);
if (prevHead != null) {
newHead.connectRight(prevHead);
} else {
tail = newHead;
}
head = newHead;
size++;
checkInvariants();
}
public void addLast(T item) {
Node<T> newTail = new Node<T>(item);
Node<T> prevTail = tail;
if (prevTail != null) {
prevTail.connectRight(newTail);
} else {
head = newTail;
}
tail = newTail;
size++;
checkInvariants();
}
public T removeFirst() {
if (isEmpty()) {
throw new java.util.NoSuchElementException();
}
size--;
Node<T> prevHead = head;
head = prevHead.right;
prevHead.right = null;
if (head != null) {
head.left = null;
}
checkInvariants();
return prevHead.item;
}
public T removeLast() {
if (isEmpty()) {
throw new java.util.NoSuchElementException();
}
size--;
Node<T> prevTail = tail;
tail = prevTail.left;
prevTail.left = null;
if (tail != null) tail.right = null;
checkInvariants();
return prevTail.item;
}
#Override
public String toString() {
Node<T> currTail = tail;
Node<T> currHead = head;
head = currHead.right;
tail = currTail.left;
StringBuilder builder = new StringBuilder();
while (currHead != null && currTail != null) {
builder.append(currHead.item + "\n");
}
return builder.toString();
}
public static void main(String[] args) {
Deque<Double> d = new Deque<Double>();
d.addFirst(1.0);
System.out.println(d);
d.addLast(1.0);
//d.removeFirst();
//d.removeLast();
System.out.println(d.toString());
}
}
First of all, you're setting the instance variables head and tail to their respective neighbours, which is definitely not what you're out to do. This leaves your queue in an inconsistent state, where the second element is the head, but it still has a left neighbour, the original head. Same thing for the tail. Generally the toString method shouldn't have side effects.
Neither currTail nor currHead ever change in your while-loop, so your condition currHead != null && currTail != null will always be true if the deque is non-empty. You'd have to set those variables in the loop, however, you don't need to iterate from both ends at once. Iterating from the start will be enough. And then, you can use a for loop, like this:
#Override
public String toString() {
final StringJoiner stringJoiner = new StringJoiner("\n");
for (Node<T> node = head; node != null; node = node.right) {
stringJoiner.add(node.item.toString());
}
return stringJoiner.toString();
}
This sets the variable node to it's right neighbour after every iteration, and if the deque is empty, node will be null from the get-go and the loop will not be entered as is expected.
This is just the more concise (In my opinion) version of this:
#Override
public String toString() {
final StringJoiner stringJoiner = new StringJoiner("\n");
Node<?> node = head;
while (node != null) {
stringJoiner.add(node.item.toString());
node = node.right;
}
return stringJoiner.toString();
}
which is basically your attempt, just fixed.
Not that I've used a StringJoiner instead of a StringBuilder, as it allows you to set a delimeter that is used between each String, which is exactly what you're doing.
I have made my own implementation of a generic Linked Queue for class, it is pretty much finished, here it is:
public class LinkedQueue<T> implements Queue<T> {
//Using head & tail approach.
private myNode<T> head;
private myNode<T> tail;
private int size;
public LinkedQueue(){
this.head = null;
this.tail = head;
this.size = 0;
}
public myNode<T> getterHead(){ //couldn't bring myself to write "get" instead of "getter"
return this.head;
}
#Override
public int size() {
return this.size; //returns number of nodes
}
#Override
public boolean isEmpty() {
return this.head==null;
}
#Override
public void enqueue(T element) {
if(isEmpty()){
this.head = new myNode<T>(element);
this.tail = head;
size++;
}
else{
this.tail.next = new myNode<T>(element);
this.tail = tail.next;
size++;
}
}
#Override
public T dequeue() {
if(isEmpty())throw new NoSuchElementException("This queue is empty");
T returnObj = this.head.data; //saving the data of the first element(head)
//If there are at least 2 nodes, else.
if(head != tail){
this.head = head.getNext();
size--;
}
else{
this.head = null;
this.tail = head;
this.size = 0;
}
return returnObj;
}
#Override
public T first() {
return this.head.data;
}
#Override
public T last() {
return this.tail.data;
}
/* I absolutely can not get past this NullPointerException that is given every time
* I try to use the iterator. It seems that current.next is always null(doesn't point to head properly?).
* HOWEVER, if you change "curr" for "head", it works. */
#Override
public Iterator<T> iterator() {
return new GenericIterator();
}
private class GenericIterator implements Iterator<T>{
public myNode<T> curr = head;
public boolean hasNext() {
return (head != null && head.next != null);
}
public T next() {
T tmp = head.data; //saving current in a temporary node because we are changing the value of current in the next line
if(hasNext()){
head = head.next;
}
return tmp;
}
}
private class myNode<T> { //parameter type T hiding type T
public T data; //The generic data the nodes contain
public myNode<T> next; //Next node
//Node constructor
public myNode(T nData) {
this.data = nData;
this.next = null;
}
public myNode<T> getNext(){
return this.next;
}
}
}
Here is the part that is giving me trouble:
/* I absolutely can not get past this NullPointerException that is given every time
* I try to use the iterator. It seems that current.next is always null(doesn't point to head properly?).
* HOWEVER, if you change "curr" for "head", it works. */
#Override
public Iterator<T> iterator() {
return new GenericIterator();
}
private class GenericIterator implements Iterator<T>{
public myNode<T> curr = head; //doesn't work with getter either.
//public myNode<T> curr = getterHead();
public boolean hasNext() {
return (curr != null && curr.next != null);
}
public T next() {
T tmp = curr.data; //NPE HERE!
if(hasNext()){
curr = curr.next;
}
return tmp;
}
}
What I have tried is getters/setters and triple-checking every other method(they work). What seems to be the problem is that when I assign curr = head, it seems that the properties from myNode do not come with.
While head.next works fine, curr.next == null, even curr.data == null while head.data works.
I've tried with public properties and printing LinkedQueue.head.next etc, it works fine.
Stacktrace:
Exception in thread "main" java.lang.NullPointerException
at dk222gw_lab4.Queue.LinkedQueue$GenericIterator.next(LinkedQueue.java:101)
at dk222gw_lab4.Queue.LinkedQueueMain.main(LinkedQueueMain.java:17)
Where line 101 & 17 are:
T tmp = curr.data; //node property .data & .next are null.
System.out.println(it.next()); //LinkedQueueMain.java(not included in post), both it.next() and it.hasNext() produce this NPE.
I have created a queue implementation using a single connection list.In this code I am using 2 pointers (first,last) to define the start and the end of my queue. My code is :
import java.io.PrintStream;
import java.util.*
/**
* #author Justin Bieber
*/
public class StringQueueImpl<T> implements StringQueue {
private int total; // number of elements on queue
private Node head; // beginning of queue
private Node tail; // end of queue
private class Node {
T ele;
Node next;
Node(T ele) {
this.ele = ele;
next = null; }
}
/**
* Creates an empty queue.
*/
public StringQueueImpl() {
first = null;
last = null;
total = 0;
}
boolean isEmpty() {
return (head == null);
}
public <T> void put(T ele) {
Node t = tail;
tail = new Node(ele);
if (isEmpty()) head = tail;
else t.next = tail;
total++;
}
public T get() {
if (isEmpty()) throw new NoSuchElementException();
T v = head.ele;
Node t = head.next;
head = t;
return v;
total--;
}
public T peek() {
if (isEmpty()) throw new NoSuchElementException();
return head.ele;
}
Node node = head;
public void printQueue(PrintStream stream){
while(node != null){
stream.println(node.ele);
stream.flush();
node = node.next;
}
}
public int size(){
return total;
}
}
My question is how can I create a queue implementation using a circular list. (Instead of 2 pointers for the start and the end I would like to use only one pointer wich will be used for both the start and the end of the queue).
Any help is apreciated . Thank you
I have created a linked list in java, the issue is with
public void add(T data)
when I try to add some thing at the end of the list, "null" is getting added to the end of the list. I think there is some problem with my iterator which is not able to find the last node.
Plz help.
public class LinkedList<T> implements Iterable<T> {
private Node<T> head;
/**
* Default constructor
*
* #param head
*/
public LinkedList() {
super();
this.head = new Node<T>(null);
}
/**
* Inserts a new node at the beginning of this list.
*/
public void addFirst(T data) {
Node<T> newNode = new Node<T>(data, head);
head = newNode;
}
public void add(T data) {
Node<T> tempNpde = head;
while (tempNpde.next != null) {
tempNpde = tempNpde.next;
}
tempNpde.next = new Node<T>(data, null);
}
/**
*
* #param head
* #return
*/
public T getNode() {
return head.data;
}
#Override
public Iterator<T> iterator() {
return new ListIterator<T>();
}
public class ListIterator<T> implements Iterator<T> {
private Node<T> currentNode;
/**
* #param currentNode
*/
public ListIterator() {
super();
this.currentNode = (Node<T>) head;
}
#Override
public boolean hasNext() {
if (currentNode != null && currentNode.next != null)
return true;
else
return false;
}
#Override
public T next() {
if (!hasNext())
throw new NoSuchElementException();
T node = currentNode.data;
currentNode = currentNode.next;
return node;
}
#Override
public void remove() {
// TODO Auto-generated method stub
}
}
// Same as using struct in C
private static class Node<T> {
private T data;
private Node<T> next;
/**
* #param data
* #param next
*/
public Node(T data, Node<T> next) {
super();
this.data = data;
this.next = next;
}
/**
* #param next
*/
public Node(Node<T> next) {
super();
this.data = null;
this.next = next;
}
}
public static void main(String[] args) {
LinkedList<String> list = new LinkedList<String>();
list.addFirst("aaaa");
list.addFirst("bbbb");
list.add("dddd");
Iterator<String> itr = list.iterator();
while (itr.hasNext()) {
System.out.println(itr.next());
}
}
As was already said, the biggest issue was that your next() wasn't doing what you thought it was... try this:
public class LinkedList<T> implements Iterable<T> {
private Node<T> head;
/**
* Default constructor
*
* #param head
*/
public LinkedList() {
super();
this.head = null;
}
/**
* Inserts a new node at the beginning of this list.
*/
public void addFirst(T data) {
Node<T> newNode = new Node<T>(data, head);
head = newNode;
}
public void add(T data) {
if ( head == null )
{
head = new Node<T>(data, null);
return;
}
Node<T> tempNode = head;
while (tempNode.next != null) {
tempNode = tempNode.next;
}
tempNode.next = new Node<T>(data, null);
}
/**
* #param head
* #return
*/
public T getNode() {
return head.data;
}
#Override
public Iterator<T> iterator() {
return new ListIterator<T>();
}
public class ListIterator<T> implements Iterator<T> {
private Node<T> currentNode;
private Node<T> previous;
/**
* #param currentNode
*/
public ListIterator() {
super();
this.currentNode = (Node<T>) head;
this.previous = null;
}
#Override
public boolean hasNext() {
if (currentNode != null && currentNode.next != null)
return true;
else
return false;
}
#Override
public T next() {
if (!hasNext())
throw new NoSuchElementException();
if ( previous == null )
{
previous = currentNode;
return previous.data;
}
T node = currentNode.data;
currentNode = currentNode.next;
return currentNode.data;
}
#Override
public void remove() {
// TODO Auto-generated method stub
}
}
// Same as using struct in C
private static class Node<T> {
private T data;
private Node<T> next;
/**
* #param data
* #param next
*/
public Node(T data, Node<T> next) {
super();
this.data = data;
this.next = next;
}
/**
* #param next
*/
public Node(Node<T> next) {
super();
this.data = null;
this.next = next;
}
}
public static void main(String[] args) {
LinkedList<String> list = new LinkedList<String>();
list.add("aaaa");
list.add("bbbb");
list.addFirst("cccc");
list.add("dddd");
list.add("eeee");
list.add("ffff");
for ( String s : list ) // same thing as using an iterator
System.out.println(s);
}
}
This is the entirety of the class. This should fix the functionality for you, but if you spot any unsatisfactory changes (e.g. changing the head to initially be null instead of a node with null data), let me know...
A much simpler solution is to just modify your ListIterator#hasNext() implementation as
#Override
public boolean hasNext() {
if (currentNode != null)
return true;
else
return false;
}
The reason your last element isn't getting covered by your ListIterator is that it will always return false for currentNode.next != null because it's at the end.
Removing this condition doesn't break your iterator implementation. With the above changes, when your ListIterator is at the last element, hasNext() returns true now. The subsequent next() call returns the currentNode.data and points the ListIterator to null which then breaks the iteration loop as required.
So basically, your ListIterator#next() implementation was just fine.
Why not simply keep track of Head and Tail as two separate fields and, when you need to add a new node, set Tail.next to your new node and then set Tail to the new node? Iterating through the entire list every time you want to add something is terribly inefficient.
Also, to directly answer your question, your iterator is broken. Take a look at what your next() method is doing. Is it, in fact, returning the next Node?