I've created a CircularLinkedList class, instead of using the util LinkedList class. The problem is based off of the Josephus problem, stating that for a circle of 20 people, each 12th person is to be killed until it is determined which position the survivor will be left standing in (using an Iterator). I'm confused as to how I could use an Iterator with this problem, since I'm using my own class instead of LinkedList, which already has an iterator() method so that I could declare an Iterator like this:
Iterator<E> iter = cll.iterator();
I have no idea how I would write my own Iterator method, and I feel like I have to be over thinking this. Any help is appreciated! I can post my code if it would clear anything up that I forgot to mention
I'm still stuck on this, so I figured I'd post my code to see if anyone can help. It's a lot, so I apologize.
Itr class (Iterator)
import java.util.Iterator;
public class Itr<E> extends CircularLinkedList<E> implements Iterator<E>
{
/** the size of the list */
private int size = 0;
/** for the hasNext() method for Iterator */
private int nextNode = 0;
/** two Nodes used for next() method for Iterator */
private Node<E> lastReturned = null;
private Node<E> nextUp;
/** part of the Iterator implementation */
public boolean hasNext()
{
return nextNode < size;
}
/** part of the Iterator implementation */
public E next()
{
lastReturned = nextUp;
nextUp = nextUp.getNext();
nextNode++;
return lastReturned.data;
}
/** part of the Iterator implementation */
public void remove()
{
Node<E> lastNext = lastReturned.getNext();
if (lastReturned == null)
nextUp = lastNext;
else
nextNode--;
lastReturned = null;
}
}
Josephus class
public class Josephus<E>
{
public static void main(String[] args)
{
CircularLinkedList cll = new CircularLinkedList();
Itr iter = cll.iterator();
int lastMan = 0;
int n = 20;
int passes = 12;
while(n > 1)
{
iter.next();
for(int i = 0; i < n; i += passes)
{
iter.hasNext();
iter.remove();
if(n == 1)
lastMan = n;
}
}
System.out.println("Survior: " + lastMan);
}
}
CircularLinkedList class
public class CircularLinkedList<E>
{
public class Node<E>
{
/* data value **/
public E data;
/* the link **/
private Node<E> next = null;
/** constructs a Node with given data and link
* #param data the data value
* #param next the link
*/
public Node(E data, Node<E> next)
{
this.data = data;
this.next = next;
}
/** construct a Node with given data value
* #param data the data value
*/
public Node(E data)
{
this.data = data;
}
/** return the data value of a Node
* #return the data value
*/
public E getData()
{
return data;
}
/** set the next Node in a list
* #param append the data value that the new Node will contain
*/
public void setNext(Node append)
{
next = append;
}
/** return the next Node
* # return the next Node
*/
public Node<E> getNext()
{
if(current.next == null)
current.next = current;
return next;
}
}
/** a reference into the list */
private Node<E> current = null;
/** the size of the list */
private int size = 0;
/** helper methods */
/** remove the first occurance of element item.
* #param item the item to be removed
* #return true if item is found and removed; otherwise, return false.
*/
public void removeItem(E item)
{
Node<E> position = current;
Node<E> nextPosition1,
nextPosition2;
while (position.next != null)
{
if(position.getNext().getData().equals(item))
{
nextPosition1 = position.getNext();
nextPosition2 = nextPosition1.getNext();
position.setNext(nextPosition2);
}
else
{
position = position.getNext();
}
}
}
/** set the first Node in a list
* #param append the data value that the new Node will contain
*/
public void addFirst(E append)
{
current = new Node<E>(append, current);
size++;
}
/** add a new Node as the last in the List
* #param data value of the new Node
*/
public void addNext(E value)
{
// location for new value
Node<E> temp = new Node<E>(value,null);
if (current != null)
{
// pointer to possible tail
Node<E> finger = current;
while (finger.next != null)
{
finger = finger.next;
}
finger.setNext(temp);
} else current = temp;
size++;
}
/** return the data value of the fourth Node in the list
* #return the data value
*/
public E printFourth()
{
current.next.next.next = current;
return current.next.next.next.getData();
}
/** return the size of the LinkedList
* #return the size
*/
public int size()
{
return size;
}
public E get(int index)
{
Node<E> temp = null;
for(int i = 0; i < index; i++)
{
temp = current.next;
System.out.print(temp.getData() + " ");
}
return temp.getData();
}
public Itr<E> iterator()
{
return new Itr<E>();
}
#Override
public String toString()
{
StringBuilder sb = new StringBuilder();
sb.append("[");
Node<E> aux = this.current;
boolean isFirst = true;
while(aux != null)
{
if(!isFirst)
{
sb.append(", ");
}
isFirst = false;
sb.append(aux.data.toString());
aux=aux.next;
}
return sb.append("]").toString();
}
}
I'm getting a NullPointerException from the next() method in the Itr class on the line
nextUp = nextUp.getNext();
Am I doing something wrong in the CircularLinkedList class for it to not actually be circular or is there a problem with my driver/Itr classes? I'm kind of lost at this point. Any help is appreciated.
Create a custom class which implements Iterator and return the custom Iterator from your CLL.iterator method.
See LinkedList#ListItr for inspiration - but only conside the Iterator methods (next, hasNext, remove) for this exercise. A true circular linked-list will simply follow the next node, always, and has no end - hasNext will always return true if there is at least one element. If your CLL implementation has an "end", then make sure to "move back to the start" when it is encountered.
In addition, the CLL class should conform to Iterable, which means it has an iterator method to obtain an Iterator.
Related
I am trying to implement a doubly linked list, and I am testing it with an iterator. For some reason the dll returns null at the end of the list and I can't figure out why. I would greatly appreciate an expert eye to spot what I am missing. Thanks in advance
test:
void testIterator() {
DoublyLinkedList<Integer> ll = new DoublyLinkedList<>();
for(int i = 0; i < 5; ++i) ll.addLast(i);
ArrayList<Integer> buf = new ArrayList<>();
for(Integer i : ll) {
buf.add(i);
}
assertEquals("[0, 1, 2, 3, 4]", buf.toString());
}
The test returns:
expecting [0, 1, 2, 3, 4] but was [0, 1, 2, 3, 4,null]
The Doubly Linked List
import java.util.Iterator;
public class DoublyLinkedList<E> implements List<E> {
/** Sentinel node at the beginning of the list */
private Node<E> header; // header sentinel
/** Sentinel node at the end of the list */
private Node<E> trailer; // trailer sentinel
/** Number of elements in the list (not including sentinels) */
private int size = 0;
//---------------- nested Node class ----------------
/**
* Node of a doubly linked list, which stores a reference to its
* element and to both the previous and next node in the list.
*/
private static class Node<E> {
private E data;
private Node<E> next;
private Node<E> previous;
public Node(E data, Node<E> previous,Node<E> next)
{
this.data = data;
this.next = next;
this.previous = previous;
}
public E getData()
{
return data;
}
public Node<E> getNext()
{
return next;
}
public Node<E> getPrevious()
{
return previous;
}
public void setNext(Node<E> n)
{
next = n;
}
public void setPrevious(Node<E> p)
{
previous = p;
}
public void setData(E d)
{
data = d;
}
} //----------- end of nested Node class -----------
// instance variables of the DoublyLinkedList
// number of elements in the list
/** Constructs a new empty list. */
public DoublyLinkedList() {
header = new Node<>(null, null, null);
trailer = new Node<>(null, header, null);
header.setNext(trailer);
}
// public accessor methods
/**
* Returns the number of elements in the linked list.
* #return number of elements in the linked list
*/
public int size() { return size; }
/**
* Tests whether the linked list is empty.
* #return true if the linked list is empty, false otherwise
*/
public boolean isEmpty() { return size == 0; }
#Override
public E get(int i) throws IndexOutOfBoundsException {
if((i>size()-1) || isEmpty()) {
throw new IndexOutOfBoundsException("It is not possible to get this indexed value");
}
Node<E> current = header.getNext();
for(int j=0;j<i && current != trailer;j++) {
current = current.getNext();
}
return current.getData();
}
#Override
public E set(int i, E e) throws IndexOutOfBoundsException {
Node<E> current = header.getNext();
if (isEmpty() || i > size()-1)
{
throw new RuntimeException("cannot delete either index too big or list is empty");
}
for(int j =0; j<i;j++) {
current = current.getNext();
}
current.setData(e);
return current.getData();
}
#Override
public void add(int i, E e) throws IndexOutOfBoundsException {
if (i < 0|| i > size()-1)
{
throw new RuntimeException("cannot delete either index too big or list is empty");
}
else {
Node<E> current = header.getNext();
for(int j = 0; j< i;j++) {
current = current.getNext();
}
addBetween(e,current.getPrevious(),current);
}
}
#Override
public E remove(int i) throws IndexOutOfBoundsException {
if (isEmpty() || i > size()-1)
{
throw new RuntimeException("cannot delete either index too big or list is empty");
}
Node<E> current = header.getNext();
Node<E> previous = header;
//find the correct node to remove
for (int k = 0; k < i; k++)
{
previous = current;
current = current.getNext();
}
Node<E> next =current.getNext();
previous.setNext(next);
next.setPrevious(previous);
size--;
return current.getData();
}
#Override
public Iterator<E> iterator() {
return new DoublyLinkedListIterator();
}
private class DoublyLinkedListIterator implements Iterator<E> {
private Node<E> current;
public DoublyLinkedListIterator() {
current = header.getNext();
}
#Override
public boolean hasNext() {
return current != null;
}
#Override
public E next() {
if(!hasNext()) throw new RuntimeException("No such element");
E res = current.getData();
current = current.getNext();
return res;
}
}
/**
* Returns (but does not remove) the first element of the list.
* #return element at the front of the list (or null if empty)
*/
public E first() {
// TODO
return header.getNext().getData();
}
/**
* Returns (but does not remove) the last element of the list.
* #return element at the end of the list (or null if empty)
*/
public E last() {
// TODO
return trailer.getPrevious().getData();
}
// public update methods
/**
* Adds an element to the front of the list.
* #param e the new element to add
*/
public void addFirst(E e) {
addBetween(e,header,header.getNext());
}
/**
* Adds an element to the end of the list.
* #param e the new element to add
*/
public void addLast(E e) {
addBetween(e,trailer.getPrevious(),trailer);
}
/**
* Removes and returns the first element of the list.
* #return the removed element (or null if empty)
*/
public E removeFirst() {
Node<E> current = header.getNext();
remove(0);
return current.getData();
}
/**
* Removes and returns the last element of the list.
* #return the removed element (or null if empty)
*/
public E removeLast() {
return remove((this.size()-1));
}
// private update methods
/**
* Adds an element to the linked list in between the given nodes.
* The given predecessor and successor should be neighboring each
* other prior to the call.
*
* #param predecessor node just before the location where the new element is inserted
* #param successor node just after the location where the new element is inserted
*/
private void addBetween(E e, Node<E> predecessor, Node<E> successor) {
Node<E> newNode = new Node(e,predecessor,successor);
predecessor.setNext(newNode);
successor.setPrevious(newNode);
this.size++;
}
/**
* Removes the given node from the list and returns its element.
* #param node the node to be removed (must not be a sentinel)
*/
/**
* Produces a string representation of the contents of the list.
* This exists for debugging purposes only.
*/
public String toString() {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("[");
Node<E> current = header.getNext();
while (current.getNext() != null && current != null)
{
stringBuilder.append(current.getData());
stringBuilder.append(", ");
current = current.getNext();
}
stringBuilder.replace(stringBuilder.length()-2, stringBuilder.length(), "");
stringBuilder.append("]");
return stringBuilder.toString();
}
public static void main(String [] args) {
//ArrayList<String> all;
//LinkedList<String> ll;
DoublyLinkedList<String> ll = new DoublyLinkedList<String>();
String[] alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".split("");
for (String s : alphabet) {
ll.addFirst(s);
ll.addLast(s);
}
System.out.println(ll.toString());
for (String s : ll) {
System.out.print(s + ", ");
}
}
} //----------- end of DoublyLinkedList class -----------```
I am trying to implement the set method where you pass in the position in a linked list that you want and the value and the set function adds that value into the position specified in the linked list. I have implemented the set function but for some reason The last element disappears in my implementation. I would greatly appreciate any help. Thanks in advance. I would appreciate any expert eyes that will see what I am missing.
/**
* A basic singly linked list implementation.
*/
public class SinglyLinkedList<E> implements Cloneable, Iterable<E>, List<E> {
//---------------- nested Node class ----------------
/**
* Node of a singly linked list, which stores a reference to its
* element and to the subsequent node in the list (or null if this
* is the last node).
*/
private static class Node<E> {
E value;
Node<E> next;
public Node(E e)
{
value = e;
next = null;
}
}
//----------- end of nested Node class -----------
// instance variables of the SinglyLinkedList
private Node<E> head = null; // head node of the list (or null if empty)
private int size = 0; // number of nodes in the list
public SinglyLinkedList() {
} // constructs an initially empty list
// access methods
/**
* Returns the number of elements in the linked list.
*
* #return number of elements in the linked list
*/
public int size() {
return size;
}
/**
* Adds an element to the end of the list.
*
* #param e the new element to add
*/
public void addLast(E e) {
// TODO
}
/**
* Tests whether the linked list is empty.
*
* #return true if the linked list is empty, false otherwise
*/
public boolean isEmpty() {
return size == 0;
}
#Override
public E get(int i) throws IndexOutOfBoundsException {
Node<E> a = head;
if(i<=this.size()) {
int count = 0;
while(count < i) {
count ++;
a = a.next;
}
return a.value;
}
return null;
}
#Override
public E set(int i, E e) throws IndexOutOfBoundsException {
Node<E> current = head;
Node<E> setNode = new Node<E>(e);
if(i==0) {
this.addFirst(e);
}
else if(i==this.size){
this.addLast(e);
}
else {
for(int j=0; current != null && j < (i-1);j++) {
current = current.next;
}
Node<E> temp = current.next;
current.next = setNode;
setNode.next = temp;
}
return setNode.value;
}
// update methods
/**
* Adds an element to the front of the list.
*
* #param e the new element to add
*/
public void addFirst(E e) {
Node<E> first = new Node<>(e);
first.next = this.head;
this.head = first;
this.size++;
}
#SuppressWarnings({"unchecked"})
public boolean equals(Object o) {
// TODO
return false; // if we reach this, everything matched successfully
}
#SuppressWarnings({"unchecked"})
public SinglyLinkedList<E> clone() throws CloneNotSupportedException {
// TODO
return null;
}
/**
* Produces a string representation of the contents of the list.
* This exists for debugging purposes only.
* #return
*/
public String toString() {
for(int i=0;i<this.size();i++) {
System.out.println(this.get(i));
}
return "end of Linked List";
}
public static void main(String[] args) {
SinglyLinkedList <Integer> ll =new SinglyLinkedList <Integer>();
ll.addFirst(5);
ll.addFirst(4);
ll.addFirst(3);
ll.addFirst(2);
ll.set(1,0);
System.out.println(ll);
}
}
Assumptions
addLast method is missing in the code
The error could be there too
Known cause
This code is not incrementing the size inside the set method's for loop.The size is incremented in addLast(possibly) and addFirst and not incremented in other case (final else part)
It is not clear what is planned to do with set method. The way it is implemented now, it behaves more like insert, meaning that it will add new node, bit it does not increase the total count of elements (size).
It the set method is changing the value of the node, which name indicates, then this part is wrong:
else {
for(int j=0; current != null && j < (i-1);j++) {
current = current.next;
}
Node<E> temp = current.next;
current.next = setNode;
setNode.next = temp;
}
It should replace the value instead of adding the new one:
else {
for(int j=0; current != null && j < (i-1);j++) {
current = current.next;
}
current.value=e
}
Also, it looks like the index i is 1-based, while everything else is 0 based. I didn't check the code above, but the concept should be like shown.
Hot Potato Game: In this program you are expected to implement a
general simulation of the Hot Potato game. In this game children line
up in a circle and pass an item from neighbor to neighbor as fast as
they can. At a certain point in the game, the action is stopped and
the child who has the item (the potato) is removed from the circle.
Play continues until only one child is left. In your implementation
user should input a list of names and a constant num. Your program
must return the name of the last person remaining after repetitive
counting by num.
I needed to do that but i couldn't find out how to stop that while loop in the enqueuer() method of hotpotato class. If i have some other mistakes can you please tell me?
hotpotato class:
import java.util.*;
public class hotpotato
{
private static Scanner input1 = new Scanner(System.in);
private static NodeQueue<String> potato = new NodeQueue<String>();
private static Scanner input = new Scanner(System.in);
static int num;
public static void main(String[] args)
{
System.out.println("Enter names of the children.");
enqueuer(input1.next());
System.out.println("Enter the num");
num = input.nextInt();
potatothrower();
}
public static void enqueuer(String p)
{
String keyboard = input1.next();
while(!keyboard.equals("stop"))
{
potato.enqueue(p);
}
}
public static void potatothrower()
{
for(int i = 0; i< num; i++)
{
if(!potato.isEmpty()){
String tmp = potato.front();
potato.dequeue();
potato.enqueue(tmp);
}
else{
System.out.println("Queue is empty");
}
}
potato.dequeue();
}
}
Node Class:
public class Node<E> {
// Instance variables:
private E element;
private Node<E> next;
/** Creates a node with null references to its element and next node. */
public Node() {
this(null, null);
}
/** Creates a node with the given element and next node. */
public Node(E e, Node<E> n) {
element = e;
next = n;
}
// Accessor methods:
public E getElement() {
return element;
}
public Node<E> getNext() {
return next;
}
// Modifier methods:
public void setElement(E newElem) {
element = newElem;
}
public void setNext(Node<E> newNext) {
next = newNext;
}
}
NodeQueue Class:
public class NodeQueue<E> implements Queue<E> {
protected Node<E> head;
protected Node<E> tail;
protected int size; // number of elements in the queue
public NodeQueue() { // constructs an empty stack
head = null;
tail = null;
size = 0;
}
public void enqueue(E elem) {
Node<E> node = new Node<E>();
node.setElement(elem);
node.setNext(null); // node will be new tail node
if (size == 0)
head = node; // special case of a previously empty queue
else
tail.setNext(node); // add node at the tail of the list
tail = node; // update the reference to the tail node
size++;
}
public E dequeue() {
if (size == 0)
System.out.println("Queue is empty.");
E tmp = head.getElement();
head = head.getNext();
size--;
if (size == 0)
tail = null; // the queue is now empty
return tmp;
}
public int size() { return size; }
public boolean isEmpty() {
return size == 0;
}
public E front() {
if (isEmpty()) System.out.println("Queue is empty.");
return head.getElement();
}
public String toString() {
Node<E> temp = head;
String s;
s = "[";
for (int i = 1; i <= size(); i++){
if(i==1)
s += temp.getElement();
else
s += ", " + temp.getElement();
temp = temp.getNext();
}
return s + "]";
}
}
Queue interface:
public interface Queue<E> {
/**
* Returns the number of elements in the queue.
* #return number of elements in the queue.
*/
public int size();
/**
* Returns whether the queue is empty.
* #return true if the queue is empty, false otherwise.
*/
public boolean isEmpty();
/**
* Inspects the element at the front of the queue.
* #return element at the front of the queue.
* #exception EmptyQueueException if the queue is empty.
*/
public E front();
/**
* Inserts an element at the rear of the queue.
* #param element new element to be inserted.
*/
public void enqueue (E element);
/**
* Removes the element at the front of the queue.
* #return element removed.
* #exception EmptyQueueException if the queue is empty.
*/
public E dequeue();
}
call:
System.out.println("Enter names of the children.");
enqueuer();
You're doing the read data only once and then enters an infinite WHILE loop because you have no way to write "stop". Therefore the function would be:
public static void enqueuer()
{
String p;
do {
p = input1.next();
if (!p.equals("stop"))
potato.enqueue(p);
} while(!p.equals("stop"));
}
The problem is really easy, just look better at your code:
public static void enqueuer(String p)
{
String keyboard = input1.next();
while(!keyboard.equals("stop"))
{
potato.enqueue(p);
}
}
You get the new input before the while. This means that keyboard will be the first argument, say Alice.
So, while alice != stop, do potato.enqueue.(p).
But since you get no new input inside the while, keyboard will ever be != then stop!
Bonus:
There is a bug i think:
public static void enqueuer(String p)
{
String keyboard = input1.next();
while(!keyboard.equals("stop"))
{
potato.enqueue(p); //you dont insert the keyboard value, but you insert every time p!
}
}
I posted a question yesterday about an issue I was having overriding the toString() for this program, but now I have a different problem. The removeItem() method is supposed to remove the node with the given data value (in this case a String name). I'm getting a NullPointerException on line 64 and I can't seem to figure it out for whatever reason. My code is below, and thanks in advance for any help.
public class StudentRegistration<E>
{
private static class Node<E>
{
/** The data value. */
private E data;
/** The link */
private Node<E> next = null;
/**
* Construct a node with the given data value and link
* #param data - The data value
* #param next - The link
*/
public Node(E data, Node<E> next)
{
this.data = data;
this.next = next;
}
/**
* Construct a node with the given data value
* #param data - The data value
*/
public Node(E data)
{
this(data, null);
}
public Node getNext()
{
return next;
}
public E getData()
{
return data;
}
public void setNext(Node append)
{
next = append;
}
}
/** A reference to the head of the list */
private Node<E> head = null;
/** The size of the list */
private int size = 0;
/** Helper methods */
/** Remove the first occurance of element item.
#param item the item to be removed
#return true if item is found and removed; otherwise, return false.
*/
public void removeItem(E item)
{
Node<E> position = head;
Node<E> nextPosition1,
nextPosition2;
while (position != null)
{
if(position.getNext().getData() == item) //NullPointerException
{
nextPosition1 = position.getNext();
nextPosition2 = nextPosition1.getNext();
position.setNext(nextPosition2);
}
else
{
position = position.getNext();
}
}
}
/** Insert an item as the first item of the list.
* #param item The item to be inserted
*/
public void addFirst(E item)
{
head = new Node<E>(item, head);
size++;
}
/**
* Remove the first node from the list
* #returns The removed node's data or null if the list is empty
*/
public E removeFirst()
{
Node<E> temp = head;
if (head != null)
{
head = head.next;
}
if (temp != null)
{
size--;
return temp.data;
} else
{
return null;
}
}
/** Add a node to the end of the list
*#param value The data for the new node
*/
public void addLast(E value)
{
// location for new value
Node<E> temp = new Node<E>(value,null);
if (head != null)
{
// pointer to possible tail
Node<E> finger = head;
while (finger.next != null)
{
finger = finger.next;
}
finger.setNext(temp);
} else head = temp;
}
#Override
public String toString()
{
StringBuilder sb = new StringBuilder();
sb.append("[");
Node<E> aux = this.head;
boolean isFirst = true;
while(aux != null)
{
if(!isFirst)
{
sb.append(", ");
}
isFirst = false;
sb.append(aux.data.toString());
aux=aux.next;
}
return sb.append("]").toString();
}
}
Until you are practised in "visualizing" data structures in your head, a good way to understand what is going on is to get a piece of paper and draw a "boxes and pointers" diagram representing the nodes in your data structure (and the relevant fields) ... the local variables in your diagram. Then "hand execute" using a pencil and eraser1.
Don't worry. Linked list insertion and deletion is notoriously tricky for beginners. (That's why it is commonly set as a class exercise in introductory Java and algorithms classes.)
1 - Note careful avoidance of International English faux-pas :-)
You have an exception when you reach the end and there is no next value.
You should be checking like this:
while (position.getNext() != null)
also use equals() instead of == operatoor:
if(position.getNext().getData().equals(item))
I am writing a ordered linked list for an assignment. We are using comparable, and I am struggling to get boolean add to work properly. I have labored over this code for two weeks now, and I am going cross-eyed looking at the code. I could really appreciate a fresh set of eyes on my code.
The code should work for Comparable data - both ints and String (not mixed though). I can get close to making each work, but not one code that stands for all. Please help me fix this, so the code works for either Strings or Ints.
I am only allowed to alter the add(), remove() and OrderedListNode classes
Update Thanks to parkydr, I was able to work out some of my issues, however, I am still getting a null point error. I am testing both int and Strings. If the String loop has a "<" in the while section then elements come back in reverse order. I will be an error for ints with that though. If I have >=, like parkydr said, then I get back the ints in proper order, but Strings get a null pointer error. How do I get both to work together?
Update2 the ints need to be in order, like in the code from AmitG.
Edit Does anyone have any ideas?
package dataStructures;
/**
* Class OrderedLinkedList.
*
* This class functions as a linked list, but ensures items are stored in ascending
order.
*
*/
public class OrderedLinkedList
{
/**************************************************************************
* Constants
*************************************************************************/
/** return value for unsuccessful searches */
private static final OrderedListNode NOT_FOUND = null;
/**************************************************************************
* Attributes
*************************************************************************/
/** current number of items in list */
private int theSize;
/** reference to list header node */
private OrderedListNode head;
/** reference to list tail node */
private OrderedListNode tail;
/** current number of modifications to list */
private int modCount;
/**************************************************************************
* Constructors
*************************************************************************/
/**
* Create an instance of OrderedLinkedList.
*
*/
public OrderedLinkedList()
{
// empty this OrderedLinkedList
clear();
}
/**************************************************************************
* Methods
*************************************************************************/
/*
* Add the specified item to this OrderedLinkedList.
*
* #param obj the item to be added
*/
public boolean add(Comparable obj){
OrderedListNode node = new OrderedListNode(obj);
OrderedListNode head2 = new OrderedListNode(obj);
OrderedListNode tail2 = new OrderedListNode(obj);
if (head2 == null)
{
head2 = node;
tail2 = node;
return true;
}
// When the element to be added is less than the first element in the list
if (obj.compareTo(head2.theItem) < 0)
{
node.next = head2;
head2 = node;
return true;
}
// When the element to be added is greater than every element in in list
// and has to be added at end of the list
if (obj.compareTo(tail2.theItem) > 0)
{
tail2.next = node;
tail2 = node;
return true;
}
//When the element to be added lies between other elements in the list
if (obj.compareTo(head2.theItem) >= 0 && obj.compareTo(tail2.theItem) <= 0)
{
OrderedListNode current = head.next;
OrderedListNode previous = head;
while (obj.compareTo(current.theItem) >= 0)
{
previous = current;
current = current.next;
}
previous.next = node;
node.next = current;
}
return true;
}
/*
* Remove the first occurrence of the specified item from this
OrderedLinkedList.
*
* #param obj the item to be removed
*/
public boolean remove(Comparable obj)
{
OrderedListNode curr = head;
OrderedListNode prev = head;
while(curr != null && ! (curr.theItem.compareTo(obj) == 0)){
prev = curr;
curr = curr.next;
}
if(curr == null)
return false;
else{
prev.next = curr.next;
curr = null;
return true;
}
}
/**
* Empty this OrderedLinkedList.
*/
public void clear()
{
// reset header node
head = new OrderedListNode("HEAD", null, null);
// reset tail node
tail = new OrderedListNode("TAIL", head, null);
// header references tail in an empty LinkedList
head.next = tail;
// reset size to 0
theSize = 0;
// emptying list counts as a modification
modCount++;
}
/**
* Return true if this OrderedLinkedList contains 0 items.
*/
public boolean isEmpty()
{
return theSize == 0;
}
/**
* Return the number of items in this OrderedLinkedList.
*/
public int size()
{
return theSize;
}
/*
* Return a String representation of this OrderedLinkedList.
*
* (non-Javadoc)
* #see java.lang.Object#toString()
*/
#Override
public String toString()
{
String s = "";
OrderedListNode currentNode = head.next;
while (currentNode != tail)
{
s += currentNode.theItem.toString();
if (currentNode.next != tail)
{
s += ", ";
}
currentNode = currentNode.next;
}
return s;
}
/**************************************************************************
* Inner Classes
*************************************************************************/
/**
* Nested class OrderedListNode.
*
* Encapsulates the fundamental building block of an OrderedLinkedList
* contains a data item, and references to both the next and previous nodes
* in the list
*/
// TODO: Implement the nested class OrderedListNode (5 points). This nested class
// should be similar to the nested class ListNode of the class LinkedList, but
// should store a data item of type Comparable rather than Object.
public static class OrderedListNode {
Comparable theItem;
OrderedListNode next;
OrderedListNode prev;
OrderedListNode( Comparable theItem ) { this( theItem, null, null ); }
OrderedListNode( Comparable theItem, OrderedListNode prev, OrderedListNode next)
{
this.theItem = theItem;
this.next = next;
this.prev = prev;
}
Comparable getData() { return theItem; }
OrderedListNode getNext() { return next; }
OrderedListNode getPrev() { return prev; }
}
// Remove - for testing only
public static void main (String[] args)
{
OrderedLinkedList list = new OrderedLinkedList();
list.add("1");
list.add("4");
list.add("3");
list.add("33");
list.add("4");
System.out.println(list.toString());
}
}
This above code works for ints for the most part except that items are stored as strings lexically. So I need help fixing that. I also need to make this code work with Strings as well. Right now the below code works with String but not ints, it also stores in reverse order since the <= changes in the while statement. Help!
Notice that the change in sign will make Strings work (albeit in reverse order):
while (obj.compareTo(current.theItem) <= 0)
Here's my latest version of add. It does not set up the prev links (I'll leave that as an "exercise for the reader").
public boolean add(Comparable obj){
OrderedListNode node = new OrderedListNode(obj);
// When the list is empty
if (head.next == tail)
{
head.next = node;
node.next = tail;
tail.prev = node;
return true;
}
// When the element to be added is less than the first element in the list
if (obj.compareTo(head.next.theItem) < 0)
{
node.next = head.next;
head.next = node;
return true;
}
//When there is an element in the list
OrderedListNode current = head.next;
OrderedListNode previous = head;
while (current != tail && node.theItem.compareTo(current.theItem) >= 0)
{
previous = current;
current = current.next;
}
previous.next = node;
node.next = current;
return true;
}
Modified program, output will be 1,3,33,4,4
if you want output like 1,3,4,4,33 then remove line 1 and line 2 from the following program and paste following code. Add and toString methods are modified.
int currentValue = Integer.parseInt(freshNode.theItem.toString());
int tempValue = Integer.parseInt(nodeToTraverse.theItem.toString());
if(currentValue>tempValue)
Complete code
/**
* Class OrderedLinkedList.
*
* This class functions as a linked list, but ensures items are stored in
* ascending order.
*
*/
public class OrderedLinkedList {
/**************************************************************************
* Constants
*************************************************************************/
/** return value for unsuccessful searches */
private static final OrderedListNode NOT_FOUND = null;
/**************************************************************************
* Attributes
*************************************************************************/
/** current number of items in list */
private int theSize;
/** reference to list header node */
private OrderedListNode head;
/** reference to list tail node */
private OrderedListNode tail;
/** current number of modifications to list */
private int modCount;
/**************************************************************************
* Constructors
*************************************************************************/
/**
* Create an instance of OrderedLinkedList.
*
*/
public OrderedLinkedList() {
// empty this OrderedLinkedList
// clear(); //work around with this method. Removed temporarily.
}
/**************************************************************************
* Methods
*************************************************************************/
/*
* Add the specified item to this OrderedLinkedList.
*
* #param obj the item to be added
*/
public void add(Comparable obj) {
OrderedListNode freshNode = new OrderedListNode(obj);
if (head == null) {
head = freshNode;
tail = freshNode;
return;
}
OrderedListNode nodeToTraverse = head;
while(nodeToTraverse!=null)
{
int result = freshNode.theItem.compareTo(nodeToTraverse.theItem); // line 1
if(result>0) // line 2
{
if(nodeToTraverse.next==null)
{
nodeToTraverse.next=freshNode;
freshNode.prev =nodeToTraverse;
break;
}
else
{
nodeToTraverse=nodeToTraverse.next;
continue;
}
}
else
{
nodeToTraverse.prev.next = freshNode;
freshNode.prev = nodeToTraverse.prev;
freshNode.next= nodeToTraverse;
nodeToTraverse.prev=freshNode;
break;
}
}
}
/*
* Remove the first occurrence of the specified item from this
* OrderedLinkedList.
*
* #param obj the item to be removed
*/
public boolean remove(Comparable obj) {
OrderedListNode curr = head;
OrderedListNode prev = head;
while (curr != null && !(curr.theItem.compareTo(obj) == 0)) {
prev = curr;
curr = curr.next;
}
if (curr == null)
return false;
else {
prev.next = curr.next;
curr = null;
return true;
}
}
/**
* Empty this OrderedLinkedList.
*/
public void clear() {
// reset header node
head = new OrderedListNode("HEAD", null, null);
// reset tail node
tail = new OrderedListNode("TAIL", head, null);
// header references tail in an empty LinkedList
head.next = tail;
// reset size to 0
theSize = 0;
// emptying list counts as a modification
modCount++;
}
/**
* Return true if this OrderedLinkedList contains 0 items.
*/
public boolean isEmpty() {
return theSize == 0;
}
/**
* Return the number of items in this OrderedLinkedList.
*/
public int size() {
return theSize;
}
/*
* Return a String representation of this OrderedLinkedList.
*
* (non-Javadoc)
*
* #see java.lang.Object#toString()
*/
#Override
public String toString() {
String s = "";
OrderedListNode temp = head;
while (temp != null) {
s = s + temp.theItem.toString()+",";
temp = temp.next;
}
return s.substring(0,s.lastIndexOf(",")); //this will remove last comma
// return s; //1,2,3,4,5,25,33, this will not remove last comma(,)
}
/**************************************************************************
* Inner Classes
*************************************************************************/
/**
* Nested class OrderedListNode.
*
* Encapsulates the fundamental building block of an OrderedLinkedList
* contains a data item, and references to both the next and previous nodes
* in the list
*/
// TODO: Implement the nested class OrderedListNode (5 points). This nested
// class
// should be similar to the nested class ListNode of the class LinkedList,
// but
// should store a data item of type Comparable rather than Object.
// Remove - for testing only
public static void main(String[] args) {
OrderedLinkedList list = new OrderedLinkedList();
/*list.add("1");
list.add("4");
list.add("3");
list.add("33");
list.add("5");
list.add("2");
list.add("25");*/
list.add("1");
list.add("4");
list.add("3");
list.add("33");
list.add("4");
System.out.println(list.toString());
}
private static class OrderedListNode {
Comparable data;
Comparable theItem;
OrderedListNode next;
OrderedListNode prev;
OrderedListNode(Comparable data) {
this(data, null, null);
}
OrderedListNode(Comparable data, OrderedListNode prev, OrderedListNode next) {
this.theItem = data;
this.next = next;
this.prev = prev;
}
Comparable getData() {
return data;
}
OrderedListNode getNext() {
return next;
}
OrderedListNode getPrev() {
return prev;
}
#Override
public String toString() {
return (String)theItem;
}
}
}
import java.util.*;
public class List {
private Node head;
private int manyNodes;
public List() {
head = null;
manyNodes = 0;
}
public boolean isEmpty() {
return ((head == null) && (manyNodes == 0));
}
public void add(int element) {
if (head == null) {
head = new Node(element, null);
manyNodes++;
} else {
head.addNodeAfter(element);
manyNodes++;
}
}
public boolean remove(int target) {
boolean removed = false;
Node cursor = head;
Node precursor;
if (head == null) {
throw new NoSuchElementException("Cannot remove from empty list");
}
if (head.getInfo() == target) {
head = head.getNodeAfter();
manyNodes--;
removed = true;
} else {
precursor = cursor;
cursor = cursor.getNodeAfter();
while ((cursor != null) && (!removed)) {
if (cursor.getInfo() == target) {
precursor.removeNodeAfter();
manyNodes--;
removed = true;
} else {
precursor = cursor;
cursor = cursor.getNodeAfter();
}
}
}
return removed;
}
public Node getFront() {
return head;
}
public int size() {
return manyNodes;
}
public Node listSort(Node source) {
source = head;
int largest = Integer.MIN_VALUE;
int smallest;
Node front;
while (source != null) {
if (source.getInfo() > largest) {
largest = source.getInfo();
}
source = source.getNodeAfter();
}
front = new Node(Node.find(head, largest).getInfo(), null);
remove(largest);
while (!isEmpty()) {
source = head;
smallest = Integer.MAX_VALUE;
while (source != null) {
if (source.getInfo() <= smallest) {
smallest = source.getInfo();
}
source = source.getNodeAfter();
}
remove(smallest);
front.addNodeAfter(smallest);
}
head = front.reverse(front);
source = head;
return source;
}
public void showList() {
Node cursor = head;
if (cursor == null) {
System.out.println("This list contains no items.");
} else {
while (cursor != null) {
System.out.print(cursor.getInfo() + " ");
cursor = cursor.getNodeAfter();
}
}
}
}//end class List