String casting error in a Doubly Linked list - java

I asked a question about this code yesterday which helped me overcome that issue, however now I am having other issues. I am taking a doubly linked list and writing the add, remove, reset, etc. functions for it. I have what should work for everything with the exception of the remove (which I am not quite sure of the error there), but the main issue is an error I keep getting:
Exception in thread "main" java.lang.ClassCastException: java.lang.String cannot be cast to support.DLLNode
at Double.add(Double.java:155)
at Double.main(Double.java:172)
I am looking for suggestions as to what I should do to fix this error and fix the last part of the remove method. Here is the code:
import ch06.lists.*;
import support.*;
public class Double<T extends Comparable<T>> implements ListInterface<T> {
protected DLLNode<T> front; //Front of list
protected DLLNode<T> rear; //Rear of list
protected DLLNode<T> curPosition; //Current spot for iteration
protected int numElements; //Number of elements in list
public Double() {
front = null;
rear = null;
curPosition = null;
numElements = 0;
}
protected DLLNode<T> find(T target) {
//While the list is not empty and the target is not equal to the current element
//curr will move down the list. If curr becomes null then return null.
//If it finds the element, return it.
DLLNode<T> curr;
curr = front;
T currInfo = curr.getInfo();
while(curr != null && currInfo.compareTo(target) != 0) {
curr = (DLLNode<T>)curr.getLink();
}
if (curr == null) {
return null;
}
else {
return curr;
}
}
public int size() {
//Return number of elements in the list
return numElements;
}
public boolean contains(T element) {
//Does the list contain the given element?
//Return true if so, false otherwise.
if (find(element) == null) {
return false;
}
else {
return true;
}
}
public boolean remove(T element) {
//While the list is not empty, curr will move down. If the element can not
//be found, then return false. Else remove the element.
DLLNode<T> curr;
curr = front;
while(curr != null) {
curr = (DLLNode<T>)curr.getLink();
}
if (find(element) == null) {
return false;
}
else {
if (curr == null) {
curr = curr.getBack();
curr = rear;
}
else if (curr == front) {
curr = (DLLNode<T>)curr.getLink();
curr = front;
}
else if (curr == rear) {
curr = curr.getBack();
curr = rear;
}
else {
//curr.getLink().setBack(curr.getBack());
//curr.getBack().setLink(curr.getLink());
}
return true;
}
}
public T get(T element) {
//Return the info of the find method.
if (find(element) == null) {
return null;
}
else {
return find(element).getInfo();
}
}
public String toString() {
DLLNode<T> curr;
curr = front;
String ans = "";
while (curr != null) {
ans = ans + " " + curr.getInfo();
curr = (DLLNode<T>)curr.getLink();
}
return ans;
}
public void reset() {
//Reset the iteration back to front
curPosition = front;
}
public T getNext() {
//Return the info of the next element in the list
DLLNode<T> curr;
curr = front;
//while (curr != null) {
//curr = (DLLNode<T>)curr.getLink();
//}
if ((DLLNode<T>)curr.getLink() == null) {
return null;
}
else {
curr = (DLLNode<T>)curr.getLink();
return curr.getInfo();
}
}
public void resetBack() {
}
public T getPrevious() {
//Return the previous element in the list
DLLNode<T> curr;
curr = front;
if ((DLLNode<T>)curr.getLink() == null) {
return null;
}
else if((DLLNode<T>)curr.getBack() == null) {
return null;
}
else {
curr = curr.getBack();
return curr.getInfo();
}
}
public void add(T element) {
//PreCondition: Assume the element is NOT already in the list
//AND that the list is not full!
DLLNode<T> curr;
DLLNode<T> newNode = (DLLNode<T>) element;
curr = front;
if (curr == null) {
front = (DLLNode<T>)element;
}
else {
newNode.setBack(curr.getBack());
newNode.setLink(curr);
curr.getBack().setLink(newNode);
curr.setBack(newNode);
curr = newNode;
}
}
public static void main(String[] args){
Double<String> d = new Double<String>();
d.add("Hello");
d.add("Arthur");
d.add("Goodbye");
d.add("Zoo");
d.add("Computer Science");
d.add("Mathematics");
d.add("Testing");
System.out.println(d);
}
}

The immediate problem is in the add(T element) method where you are casting:
DLLNode<T> newNode = (DLLNode<T>) element;
But you pass the element as a String not a DLLNode. See your main method: d.add("Hello");
When adding, do something like: DLLNode newNode = new DLLNode(element);
You can take a look at java LinkedList source (for inspiration on implementation and the right usage of generics for your problem).

In your add(T element) method, you have a line
DLLNode<T> newNode = (DLLNode<T>) element;
This cast does not work.
Clearly you wish to create a new node containing the element as info to add to your list here.
What you want is probably
DLLNode<T> newNode = new DLLNode<T>();
newNode.setInfo(element);
(I'm assuming your DLLNode has this setter, as it has other setters.)

Related

How can I Search for a node's contents in a Generic Linked List with a String Input?

I am trying to return all node contents that match a given String input. What I am trying to do is essentially a very simple search engine, where the user is able to type in a String and the program returns all characteristically similar contents it can find in the linked list. The linked list itself is built from a file, formatted as
<<Game’s Name 0>>\t<<Game’s Console 0>>\n
<<Game’s Name 1>>\t<<Game’s Console 1>>\n
where the lines are delimited with a \n and the game and its corresponding console are delimited with a \t.
My current methodology follows searching the linked list with a while loop, assigning a temporary value to the head and reassigning it to it's link as it goes down the list. Once the loop finds contents within a node that matches the current input, it stops the loop and returns the data found in the node. I have yet to try if this could be done with a for loop, as the while loop more than likely would not know when to continue once it has found a match. I am also unsure if the while loop argument is the most efficient one to use, as my understanding of it is very minimal. I believe !temp.equals(query) is stating "temp does not equal query," but I have a feeling that this could be done in a more efficient manner.
This is what I have so far, I will provide the entire Generic linked list class for the sake of context, but the method I am questioning is the very last one, found at line 126.
My explicitly stated question is how can I search through a linked list's contents and return those contents through the console.
import java.io.FileNotFoundException;
import java.util.Scanner;
public class GenLL<T>
{
private class ListNode
{
T data;
ListNode link;
public ListNode(T aData, ListNode aLink)
{
data = aData;
link = aLink;
}
}
private ListNode head;
private ListNode current;
private ListNode previous;
private int size;
public GenLL()
{
head = current = previous = null;
this.size = 0;
}
public void add(T aData)
{
ListNode newNode = new ListNode(aData, null);
if (head == null)
{
head = current = newNode;
this.size = 1;
return;
}
ListNode temp = head;
while (temp.link != null)
{
temp = temp.link;
}
temp.link = newNode;
this.size++;
}
public void print()
{
ListNode temp = head;
while (temp != null)
{
System.out.println(temp.data);
temp = temp.link;
}
}
public void addAfterCurrent(T aData)
{
if (current == null)
return;
ListNode newNode = new ListNode(aData, current.link);
current.link = newNode;
this.size++;
}
public T getCurrent()
{
if(current == null)
return null;
return current.data;
}
public void setCurrent(T aData)
{
if(aData == null || current == null)
return;
current.data = aData;
}
public void gotoNext()
{
if(current == null)
return;
previous = current;
current = current.link;
}
public void reset()
{
current = head;
previous = null;
}
public boolean hasMore()
{
return current != null;
}
public void removeCurrent()
{
if (current == head)
{
head = head.link;
current = head;
}
else
{
previous.link = current.link;
current = current.link;
}
if (this.size > 0)
size--;
}
public int getSize()
{
return this.size;
}
public T getAt(int index)
{
if(index < 0 || index >= size)
return null;
ListNode temp = head;
for(int i=0;i<index;i++)
temp = temp.link;
return temp.data;
}
public void setAt(int index, T aData)
{
if(index < 0 || index >= size || aData == null)
return;
ListNode temp = head;
for (int i = 0; i < index; i++)
temp = temp.link;
temp.data = aData;
}
public T search() throws FileNotFoundException {
Scanner keyboard = new Scanner(System.in);
System.out.println("Search: ");
String query = keyboard.nextLine();
ListNode temp = head;
while(!temp.equals(query))
temp = temp.link;
return temp.data;
//plus some sort of print function to display the result in the console
}
}
You can apply regex for every node's content, if the data type is string apply it if it is of some other datatype convert it into string if possible, else throw some exceptions.

How to write a remove method with Cyclic Doubly-Linked-List with Generic Nodes in Java

I am implementing a cyclic DoublyLinkedList data structure. Like a singly
linked list, nodes in a doubly linked list have a reference to the next node, but unlike a singly linked list, nodes in a doubly linked list also have a reference to the previous node. Additionally, because the list is "cyclic", the "next" reference in the last node in the list points to the first node in the list, and the "prev" reference in the first node in the list points to the last node in the list.
I am having trouble with my remove method with some size usage. It's the message I'm getting when I run my tests.
Here's my code:
public class DoublyLinkedList<E>
{
private Node first;
private int size;
#SuppressWarnings("unchecked")
public void add(E value)
{
if (first == null)
{
first = new Node(value, null, null);
first.next = first;
first.prev = first;
}
else
{
first.prev.next = new Node(value, first, first.prev);
first.prev = first.prev.next;
}
size++;
}
private class Node<E>
{
private E data;
private Node next;
private Node prev;
public Node(E data, Node next, Node prev)
{
this.data = data;
this.next = next;
this.prev = prev;
}
}
#SuppressWarnings("unchecked")
public void add(int index, E value)
{
if (first.data == null)
{
throw new IndexOutOfBoundsException();
} else if (index == 0)
{
first = new Node(value, first.next, first.prev);
}
else
{
Node current = first;
for (int i = 0; i < index - 1; i++)
{
current = current.next;
}
current.next = new Node(value, current.next, current.prev);
}
}
Here is the method I need help with.
The remove method should remove the element at the specified index in the list. Be sure to address the case in which the list is empty and/or the removed element is the first in the list. If the index parameter is invalid, an IndexOutOfBoundsException should be thrown.
#SuppressWarnings("unchecked")
public void remove(int index)
{
if (first.data == null)
{
throw new IndexOutOfBoundsException();
}
else if (index == 0)
{
first = first.next;
}
else
{
Node current = first.next;
for (int i = 0; i < index - 1; i++)
{
current = current.next;
}--size;
current.next = current.next.next;
}
}
Here is the rest of the code. The get method is incorrect, but I asked that in a different question.
public E get(int index)
{
if(index >= size)
{
}
return null;
//return first.data;
}
#SuppressWarnings("unchecked")
public int indexOf(E value)
{
int index = 0;
Node current = first;
while (current != current.next)
{
if (current.data.equals(value))
{
return index;
}
index++;
current = current.next;
}
return index;
}
public boolean isEmpty()
{
if (size == 0)
{
return true;
}
else
{
return false;
}
}
public int size()
{
return size;
}
This was not easy at all, however I did find the answer to my question. This is a cyclic doubly linked list. Here it is:
#SuppressWarnings("unchecked")
public void remove(int index)
{
if(index < 0 || index > size)
{
throw new IndexOutOfBoundsException();
}
Node n = first;
for(int i = 0; i < index; i++)
{
n = n.next;
}
// n points to node to remove
n.prev.next = n.next;
n.next.prev = n.prev;
if (index == 0)
{
if(size == 1)
{
first = null;
}
else
{
first = first.next;
}
}
size--;
}

Singly linked list removing element using head and tail reference

I have to implement a singly linked list for my project and I'm having trouble getting the remove method to work. I have searched on here for answers but I can't find any that incorporate the tail reference. My project needs to have a head and tail reference in the list and needs to be updated wherever necessary. This is my class and the remove method:
public class BasicLinkedList<T> implements Iterable<T> {
public int size;
protected class Node {
protected T data;
protected Node next;
protected Node(T data) {
this.data = data;
next = null;
}
}
protected Node head;
protected Node tail;
public BasicLinkedList() {
head = tail = null;
}
public BasicLinkedList<T> addToEnd(T data) {
Node n = new Node(data);
Node curr = head;
//Check to see if the list is empty
if (head == null) {
head = n;
tail = head;
} else {
while (curr.next != null) {
curr = curr.next;
}
curr.next = n;
tail = n;
}
size++;
return this;
}
public BasicLinkedList<T> addToFront(T data) {
Node n = new Node(data);
if(head == null){
head = n;
tail = n;
}
n.next = head;
head = n;
size++;
return this;
}
public T getFirst() {
if (head == null) {
return null;
}
return head.data;
}
public T getLast() {
if(tail == null){
return null;
}
return tail.data;
}
public int getSize() {
return size;
}
public T retrieveFirstElement() {
// Check to see if the list is empty
if (head == null) {
return null;
}
Node firstElement = head;
Node curr = head.next;
head = curr;
size--;
return firstElement.data;
}
public T retrieveLastElement() {
Node curr = head;
Node prev = head;
// Check to see if the list is empty
if (head == null) {
return null;
} else {
// If there's only one element in the list
if (head.next == null) {
curr = head;
head = null;
} else {
while (curr.next != null) {
prev = curr;
curr = curr.next;
}
tail = prev;
tail.next = null;
}
}
size--;
return curr.data;
}
public void remove(T targetData, Comparator<T> comparator) {
Node prev = null, curr = head;
while (curr != null) {
if (comparator.compare(curr.data, targetData) == 0) {
//Check to see if we need to remove the very first element
if (curr == head) {
head = head.next;
curr = head;
}
//Check to see if we need to remove the last element, in which case update the tail
else if(curr == tail){
curr = null;
tail = prev;
prev.next = null;
}
//If anywhere else in the list
else {
prev.next = curr.next;
curr = curr.next;
}
size--;
} else {
prev = curr;
curr = curr.next;
}
}
}
public Iterator<T> iterator() {
return new Iterator<T>() {
Node current = head;
#Override
public boolean hasNext() {
return current != null;
}
#Override
public T next() {
if(hasNext()){
T data = current.data;
current = current.next;
return data;
}
return null;
}
#Override
public void remove(){
throw new UnsupportedOperationException("Remove not implemented.");
}
};
}
}
I have went through many iterations of this method and each time I either lose the head reference, the tail reference or I don't remove the element and I am stumped trying to figure it out. For reference here is the test I'm running on it. I don't even fail the test, it just says failure trace.
public void testRemove(){
BasicLinkedList<String> basicList = new BasicLinkedList<String>();
basicList.addToEnd("Blue");
basicList.addToEnd("Red");
basicList.addToEnd("Magenta");
//Blue -> Red -> Magenta -> null
basicList.remove("Red", String.CASE_INSENSITIVE_ORDER);
//Blue -> Magenta -> null
assertTrue(basicList.getFirst().equals("Blue"));
//getLast() returns the tail node
assertTrue(basicList.getLast().equals("Magenta"));
}
EDIT: Forgot to mention that the remove method should be removing all instances of the target data from the list.
I see only 1 bug. If your list is initially empty the following method will cause a loop where you have one node whose next refers to itself:
public BasicLinkedList<T> addToFront(T data) {
Node n = new Node(data);
// The list was empty so this if is true
if(head == null){
head = n;
tail = n;
}
n.next = head;
// now head == n and n.next == head == n so you've got a circle
head = n;
size++;
return this;
}
You can fix this like so:
public BasicLinkedList<T> addToFront(T data) {
Node n = new Node(data);
if(head == null){
tail = n;
}
n.next = head;
head = n;
size++;
return this;
}

Doubly Linked List -Removal and Adding

This is a class lab, and within it I am attempting to add, remove, etc. into a doubly linked list. I have what I believe to be correct with what I have. I am having problems figuring out how to remove an object if its not the beginning or end of the list. I am having similar issues with the add method. Any advice on where to go from here and comments on my current code is very appreciated.
public class Double<T extends Comparable<T>> implements ListInterface<T> {
protected DLLNode<T> front; //Front of list
protected DLLNode<T> rear; //Rear of list
protected DLLNode<T> curPosition; //Current spot for iteration
protected int numElements; //Number of elements in list
public Double() {
front = null;
rear = null;
curPosition = null;
numElements = 0;
}
protected DLLNode<T> find(T target) {
//While the list is not empty and the target is not equal to the current element
//curr will move down the list. If curr becomes null then return null.
//If it finds the element, return it.
DLLNode<T> curr;
curr = front;
T currInfo = curr.getInfo();
while(curr != null && currInfo.compareTo(target) != 0) {
curr = (DLLNode<T>)curr.getLink();
}
if (curr == null) {
return null;
}
else {
return curr;
}
}
public int size() {
//Return number of elements in the list
return numElements;
}
public boolean contains(T element) {
//Does the list contain the given element?
//Return true if so, false otherwise.
if (find(element) == null) {
return false;
}
else {
return true;
}
}
public boolean remove(T element) {
//While the list is not empty, curr will move down. If the element can not
//be found, then return false. Else remove the element.
DLLNode<T> curr;
curr = front;
T currInfo = curr.getInfo();
while(curr != null) {
curr = (DLLNode<T>)curr.getLink();
}
if (find(element) == null) {
return false;
}
else {
if (curr == null) {
curr = curr.getBack();
curr = rear;
}
else if (curr == front) {
curr = (DLLNode<T>)curr.getLink();
curr = front;
}
else if (curr == rear) {
curr = curr.getBack();
curr = rear;
}
else {
}
return true;
}
}
public T get(T element) {
//Return the info of the find method.
if (find(element) == null) {
return null;
}
else {
return find(element).getInfo();
}
}
//public String toString() {
//}
public void reset() {
//Reset the iteration back to front
curPosition = front;
}
public T getNext() {
//Return the info of the next element in the list
DLLNode<T> curr;
curr = front;
//while (curr != null) {
//curr = (DLLNode<T>)curr.getLink();
//}
if ((DLLNode<T>)curr.getLink() == null) {
return null;
}
else {
curr = (DLLNode<T>)curr.getLink();
return curr.getInfo();
}
}
public void resetBack() {
}
public T getPrevious() {
//Return the previous element in the list
DLLNode<T> curr;
curr = front;
if ((DLLNode<T>)curr.getLink() == null) {
return null;
}
else if((DLLNode<T>)curr.getBack() == null) {
return null;
}
else {
curr = curr.getBack();
return curr.getInfo();
}
}
public void add(T element) {
//PreCondition: Assume the element is NOT already in the list
//AND that the list is not full!
DLLNode<T> curr;
DLLNode<T> newNode = (DLLNode<T>)element;
curr = front;
if (curr == null) {
front = (DLLNode<T>)element;
}
else {
}
}
}
This is the target main function eventually:
public static void main(String[] args){
Double<String> d = new Double<String>();
d.add("Hello");
d.add("Arthur");
d.add("Goodbye");
d.add("Zoo");
d.add("Computer Science");
d.add("Mathematics");
d.add("Testing");
System.out.println(d);
System.out.println( "Contains -Hello- " + d.contains("Hello"));
System.out.println("Contains -Spring- " + d.contains("Spring"));
System.out.println("size: " + d.size());
d.resetBack();
for (int i = 0; i < d.size(); i++){
String item = (String)d.getPrevious();
System.out.println(item);
} //good stopping point
d.remove("Zoo");
d.remove("Arthur");
d.remove("Testing");
System.out.println("size: " + d.size());
System.out.println(d);
d.remove("Goodbye");
d.remove("Hello");
System.out.println(d);
d.remove ("Computer Science");
d.remove("Mathematics");
System.out.println(d);}
}
I don't know what your DLLNode class looks like, but it probably looks like
class DLLNode {
DLLNode next;
DLLNode prev;
}
To remove a node, the logic would be
next.prev = prev;
prev.next = next;
To add a node newNode following a node, the logic is
newNode.prev = this;
newNode.next = next;
next = newNode;
I haven't done any null pointer checks, that's up to you.

null pointer exception in my bubblesort, and other sort methods

I have a project where I have to write a bunch of sort methods and measure the time complexity for each, and output the results to an output text file. the program runs but i get some null pointer exceptions in bubblesort method. here is my code and error, if you can tell me how to fix my sort methods, that would be awesome!
linked list class:
public class LinkedList {
protected static class Node {
Comparable item;
Node prev, next;
public Node(Comparable newItem, Node prev, Node next) {
this.item = newItem;
this.prev = prev;
this.next = next;
}
public Node (Comparable newItem) {
this(newItem, null, null);
}
public Node() {
this(null, null, null);
}
public String toString() {
return String.valueOf(item);
}
}
private Node head;
private int size;
public int dataCompares, dataAssigns;
public int loopCompares, loopAssigns;
public int other;
public LinkedList() {
head = new Node(null, null, null);
head.prev = head;
head.next = head;
size = 0;
}
public boolean add(Comparable newItem) {
Node newNode = new Node(newItem);
Node curr;
if(isEmpty()) {
head.next = newNode;
head.prev = newNode;
newNode.next = head;
newNode.prev = head;
} else {
newNode.next = head;
newNode.prev = head.prev;
head.prev.next = newNode;
head.prev = newNode;
}
size++;
return false;
}
public boolean remove(Comparable item) {
if(!isEmpty()) {
Node prev = null;
Node curr = head;
while(curr!=null) {
if(curr.item.compareTo(item)==0) {
if(prev==null) {
head=curr.next;
} else {
prev.next = curr.next;
curr=curr.next;
}
size--;
return true;
}else{
prev=curr;
curr = curr.next;
}
}
}
return false;
}
public void removeAll() {
this.head.prev = null;
this.head.next = null;
size = 0;
}
public boolean isEmpty() {
return size == 0;
}
public boolean remove(Object item) {
return true;
}
public void insertSortNode() {
Node back = head;
if (size < 2)
return;
back = back.next; // SECOND entry in the list
while ( back != null ) { // I.e., end-of-list
Comparable value = back.item;
Node curr = head; // Start at the front
// Find insertion point for value;
while (curr != back && value.compareTo(curr.item) >= 0)
curr = curr.next;
// Propogate values upward, inserting the value from back
while (curr != back){
Comparable hold = curr.item;
curr.item = value;
value = hold;
curr = curr.next;
}
back.item = value; // Drop final value into place!
back = back.next; // Move sorted boundary up
}
} // end insertSort()
public void selSort() {
Node front = head;
// Nothing to do on an empty list
if ( front == null )
return;
while ( front.next != null ) { // skips a one-entry list
Node tiny = front;
Node curr = front.next;
Comparable temp = front.item; // start the swap
for ( ; curr != null ; curr = curr.next ) {
if ( tiny.item.compareTo(curr.item) > 0 )
tiny = curr;
}
front.item = tiny.item; // Finish the swap
tiny.item = temp;
front = front.next; // Advance to the next node
}
// The structure is unchanged, so the validity of tail is unchanged.
}
public void bubbleSort() {
Node Trav=head.next;
Node Trail=head.next;
Comparable temp;
if (Trav != null)
Trav = Trav.next;
while(Trav!=null) {
if (Trav.item.compareTo(Trail.item)<0) {
temp = Trail.item;
Trail.item=Trav.item;
Trav.item = temp;
}
Trail=Trav;
Trav=Trav.next;
}
}
public void insertSortArray() {
Node insert1, cur, tmp1;
Comparable temp;
for(insert1 = this.head.next.next; insert1!=this.head; insert1 = insert1.next) {
//++loopcompares; ++loopassigns;
for (cur = head.next; cur!=insert1; cur=cur.next) {
//++loopCompares; ++loopassigns;
//++datacompares;
if(insert1.item.compareTo(cur.item)<0) {
temp=insert1.item;
//++dataassign
tmp1=insert1;
//++other
while(tmp1!=cur.prev) {
//++loopcomares
tmp1.item=tmp1.prev.item;
tmp1=tmp1.prev;
//++dataassign+=2
}
//++loopcompares
cur.item = temp;
//++dataassign;
break;
}
}
//++loopcompares; ++loopassigns;
}
//++loopcompares; ++loopassigns
}
public void disp6sortsFile(boolean disp, String fileName, String header, String data) {
FileWriter fw = null;
PrintWriter pw = null;
try {
File file = new File(fileName);
fw = new FileWriter(file, true);
pw = new PrintWriter(fw, true);
} catch (IOException e) {
System.err.println("File open failed for " +fileName+ "\n" + e);
System.exit(-1);
}
if (disp) {
pw.print(header + "\n");
}
pw.print(data + "\n");
pw.close();
}
}
here is my error:
Exception in thread "main" java.lang.NullPointerException
at LinkedList.bubbleSort(LinkedList.java:149)
at LinkListTester.main(LinkListTester.java:51)
the linkedlisttester error is simply list1.bubbleSort(); so bubble sort is the problem.
Change:
public String toString() {
return this.item.toString();
}
to:
public String toString() {
return String.valueOf(item); // Handle null too.
}
For add return true. Might check that item is not null if so desired.
remove is written for a single linked list.
In remove the head has a null item, which might have caused the error. Also as we have a circular list with a dummy node for head, the termination should not test for null but head. Otherwise a not present item will loop infinitely.
public boolean remove(Comparable item) {
if(!isEmpty()) {
Node prev = null;
Node curr = head.next; // !
while(curr!=head) { // !
if(curr.item.compareTo(item)==0) {
if(prev==null) { // ! WRONG, but I will not correct home work ;)
head=curr.next;
} else {
prev.next = curr.next;
curr=curr.next;
}
size--;
return true;
}else{
prev=curr;
curr = curr.next;
}
}
}
return false;
}
swap is written for a single linked list.
And here I stopped reading, as I've come to the usages.
Second Edit:
All algorithmic functions, i.e. bubbleSort, have the following control flow:
while(Trav!=null) { ... Trav = Trav.next; }
But the data structure is defined cyclic, so eventually you arrive back at head and there the item is null.
The solution is to have for the first Node a prev null, and for the last Node a next null.
To make this clear, readable, you could substitute the Node head with:
Node first;
Node last;

Categories

Resources