Adding to the front of an Ordered Linked List - java

I created an Ordered Linked List consisting of Nodes which contain pointers, data, and the keys used to sort them. So far in my method named "add" I have got it to successfully add after a node continually. For example, adding A then B then C. But When I try to continually add in front of a node the first node doesn't seem to have anything pointing to it or the order is incorrect.
By process of elimination it looks like the second else in the add method is where I am incorrectly pointing my nodes. How can I get the add method to add D then C then B which would then be ordered BCD?
public class OrderedLinkedList<E>{
private int size;
private int index;
private KeyedNode currentNode;
private KeyedNode previousNode;
private KeyedNode head;
/**
* Constructor that creates the head node that points to null and initializes size to 0.
*/
public OrderedLinkedList(){
head = null;
this.size = 0;
}
/**
* Method that goes through the OrderedLinkedList and adds one to counter then returns counter as the size.
*
* #return Returns the int variable counter.
*/
public int size(){
return this.size;
}
/**
*
* #param key
* #param value
* #return
*/
public E add(String key, E value){
if(currentNode == null){//takes care of empty list
currentNode = new KeyedNode(key, value);
head = currentNode;
}
else{
if(key.compareToIgnoreCase(currentNode.getKey()) < 0){//add to left
KeyedNode newNode = new KeyedNode(key, value);
if(previousNode == null){
previousNode = currentNode;
newNode.setNext(currentNode);
currentNode = newNode;
head = currentNode;
}
else{
newNode.setNext(currentNode);
previousNode = currentNode;
currentNode = newNode;
}
}
else if(key.compareToIgnoreCase(currentNode.getKey()) > 0){//add to right
KeyedNode newNode = new KeyedNode(key, value);
previousNode = currentNode;
currentNode = newNode;
currentNode.setNext(previousNode.getNext());
previousNode.setNext(currentNode);
}
}
size++;
return null;
}
/**
* Method that looks through the keys of the OrderedLinkedList nodes and returns the data of the node.
* #param key The String key parameter used to search the OrderedLinkedList.
* #return Returns the data of the node with the matching key.
*/
public E find(String key){
KeyedNode current = head;
while(current != null){
if(current.getKey().compareToIgnoreCase(key) == 0){
return current.getData();
}
else if(key.compareToIgnoreCase(current.getKey()) < 0){
return null;
}
else{
current = current.getNext();
}
}
return null;
}
/**
* Method that creates an index for the OrderedLinkedList, then uses the index to find the position of a node to return.
*
* #param position Position is an int variable used to match with index to find a node.
* #return Returns the data of the node in the desired position.
*/
public E get(int position){
KeyedNode current = head;
index = 0;
if(position < 0 || position > size){
return null;
}
while(current != null){
if(index == position){
return current.getData();
}
else{
current = current.getNext();
index++;
}
}
return null;
}
/**
* Private inner class KeyedNode of OrderedLinkedList begins.
*/
private class KeyedNode{
private String key;
private E data;
private KeyedNode next;
public KeyedNode(String keyWord, E dataItem){
data = dataItem;
key = keyWord;
next = null;
}
//getters
public E getData(){
return data;
}
public KeyedNode getNext(){
return next;
}
public String getKey(){
return key;
}
//setters
#SuppressWarnings("unused")
public void setData(E nodeData){
data = nodeData;
}
public void setNext(KeyedNode nodeNext){
next = nodeNext;
}
#Override
public String toString(){
return "The nodes key is: " + key;
}
}
/**
* private class KeyedNode ends
*/
}

Related

Add Comparable Object to Sorted Linked List

I've written an add(Comparable obj) method here: However, when I run a test on it, such as the one listed below, the printed list only consists of the most recently added item. I can't find the break in my logic.
When I try to increment theSize++ before the While loop, I receive an "Exception in thread "main" java.lang.ClassCastException: class java.lang.Character cannot be cast to class java.lang.String (java.lang.Character and java.lang.String are in module java.base of loader 'bootstrap')".
EDIT:Full code:
/**
* Class OrderedLinkedList.
* <p>
* 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) {
// TODO: Implement this method (8 points)
OrderedListNode node = new OrderedListNode(obj, null, null);
//if list is empty, add to beginning of list
if (isEmpty()) {
head.next = node;
node.next = tail;
tail.previous = node;
}
//if theItem is less than the first element, add it to the beginning of the list
if (obj.compareTo(head.next.theItem) < 0) {
node.next = head.next;
head.next = node;
}
OrderedListNode pointer = head.next;
while (pointer.theItem.compareTo(obj) < 0 && pointer.next != null) {
pointer = pointer.next;
node.previous = pointer.previous;
node.next = pointer;
pointer.previous.next = node;
pointer.previous = node;
theSize++;
modCount++;
}
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) {
// TODO: implement this method (7 points)
OrderedListNode node = head.next;
if (isEmpty()) {
return false;
}
while (node != null) {
if (obj.compareTo(node) == 0) {
node.next.previous = node.previous;
node = node.next;
return true;
}
node = node.next;
}
++modCount;
return false;
}
/**
* 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.
* <p>
* Encapsulates the fundamental building block of an OrderedLinkedList
* contains a data item, and references to both the next and previous nodes
* in the list
*/
public static class OrderedListNode {
Comparable theItem;
OrderedListNode next;
OrderedListNode previous;
OrderedListNode(Comparable item, OrderedListNode prev, OrderedListNode next) {
this.theItem = item;
this.previous = prev;
this.next = next;
}
}
// 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 void main(String[] args) { System.out.println("test");
OrderedLinkedList listOne = new OrderedLinkedList();
listOne.add('1');
listOne.add('2');
listOne.add('3');
System.out.println(listOne + " ");
}
}
Here's an edited version of the add method:
public boolean add(Comparable obj)
{
// TODO: Implement this method (8 points)
OrderedListNode node = new OrderedListNode(obj, null, null);
//if list is empty, add to beginning of list
if (isEmpty())
{
head.next = node;
node.next = tail;
tail.previous = node;
theSize++;
}
else
{
OrderedListNode pointer = head.next;
while(pointer.theItem.compareTo(obj) < 0 && pointer != tail)
{
pointer = pointer.next;
}
if(pointer == tail)
{
pointer = tail.previous;
pointer.next = node;
node.previous = pointer;
node.next = tail;
tail.previous = node;
modCount++;
}
else
{
node.previous = pointer.previous;
node.next = pointer;
pointer.previous.next = node;
pointer.previous = node;
modCount++;
}
theSize++;
}
return true;
}
This should work! I think shuffling through the list instead of just finding the right spot was causing some pointer issues...this should work!

Doubly Linked List moving item to end java

I found this code for adding an item to the front of the linked list, but since I have a last node, it doesn't work quite right, so I changed it a tiny bit:
public void moveToFront(String node) {
DoubleNode previous = first;
temp = first;
while (temp != null) {
if (node.equals(temp.item)) {
//Found the item
previous.next = temp.next;
temp.next = first;
first = temp;
if (last.next != null) {
last = last.prev;
last.prev = previous;
}
return;
}
previous = temp;
temp = temp.next;
}
The if (last.next != null) is asking if the original last was moved, and checking if the new last has the right links. Now I think it works properly for my code.
I'd like to implement this code, but for adding an item to the end. However, last just isn't right now. When calling last.prev it only gets the one item behind it, but last.prev.prev to infinity is the same item.
My idea was instead of working from first like in moveToFront(), I work from last, and step through each node backwards, but obviously that doesn't work when last doesn't work anymore.
public void moveToEnd(String node) {
DoubleNode previous = last;
temp = last;
System.out.println("last = " + last.prev.item);
System.out.println("temp = " + temp.item);
while (!temp.item.equals(first.item)) {
if(node.equals(temp.item)){
System.out.println("previous.prev = " + previous.prev.item);
}
previous = temp;
temp = temp.prev;
System.out.println("temp.prev = " + temp.prev.prev.prev.prev.prev.prev.prev.prev.prev.prev.prev.item);
}
Here's how I implement my linked list:
public class LinkedListDeque {
public DoubleNode first = new DoubleNode(null);
public DoubleNode last = new DoubleNode(null);
public DoubleNode temp;
public int N;
LinkedListDeque() {
first.next = last;
last.prev = first;
}
private class DoubleNode {
String item;
int counter = 0;
DoubleNode next;
DoubleNode prev;
DoubleNode(String i) {
this.item = i;
}
}
I found this example of a complete doubly linked list. It does not have an add to front method, but it is adding to the back of the linked list each time. Hopefully, it will help and give you a better idea of how this data structure is supposed to work and function. I would definitely test it first as it states in the readme for this GitHub that none of the code has been tested. Sorce
/*******************************************************
* DoublyLinkedList.java
* Created by Stephen Hall on 9/22/17.
* Copyright (c) 2017 Stephen Hall. All rights reserved.
* A Linked List implementation in Java
********************************************************/
package Lists.Doubly_Linked_List;
/**
* Doubly linked list class
* #param <T> Generic type
*/
public class DoublyLinkedList<T extends Comparable<T>> {
/**
* Node class for singly linked list
*/
public class Node{
/**
* private Members
*/
private T data;
private Node next;
private Node previous;
/**
* Node Class Constructor
* #param data Data to be held in the Node
*/
public Node(T data){
this.data = data;
next = previous = null;
}
}
/**
* Private Members
*/
private Node head;
private Node tail;
private int count;
/**
* Linked List Constructor
*/
public DoublyLinkedList(){
head = tail = null;
count = 0;
}
/**
* Adds a new node into the list with the given data
* #param data Data to add into the list
* #return Node added into the list
*/
public Node add(T data){
// No data to insert into list
if (data != null) {
Node node = new Node(data);
// The Linked list is empty
if (head == null) {
head = node;
tail = head;
count++;
return node;
}
// Add to the end of the list
tail.next = node;
node.previous = tail;
tail = node;
count++;
return node;
}
return null;
}
/**
* Removes the first node in the list matching the data
* #param data Data to remove from the list
* #return Node removed from the list
*/
public Node remove(T data){
// List is empty or no data to remove
if (head == null || data == null)
return null;
Node tmp = head;
// The data to remove what found in the first Node in the list
if(equalTo(tmp.data, data)) {
head = head.next;
count--;
return tmp;
}
// Try to find the node in the list
while (tmp.next != null) {
// Node was found, Remove it from the list
if (equalTo(tmp.next.data, data)) {
if(tmp.next == tail){
tail = tmp;
tmp = tmp.next;
tail.next = null;
count--;
return tmp;
}
else {
Node node = tmp.next;
tmp.next = tmp.next.next;
tmp.next.next.previous = tmp;
node.next = node.previous = null;
count--;
return node;
}
}
tmp = tmp.next;
}
// The data was not found in the list
return null;
}
/**
* Gets the first node that has the given data
* #param data Data to find in the list
* #return Node First node with matching data or null if no node was found
*/
public Node find(T data){
// No list or data to find
if (head == null || data == null)
return null;
Node tmp = head;
// Try to find the data in the list
while(tmp != null) {
// Data was found
if (equalTo(tmp.data, data))
return tmp;
tmp = tmp.next;
}
// Data was not found in the list
return null;
}
/**
* Gets the node at the given index
* #param index Index of the Node to get
* #return Node at passed in index
*/
public Node indexAt(int index){
//Index was negative or larger then the amount of Nodes in the list
if (index < 0 || index > size())
return null;
Node tmp = head;
// Move to index
for (int i = 0; i < index; i++)
tmp = tmp.next;
// return the node at the index position
return tmp;
}
/**
* Gets the current count of the array
* #return Number of items in the array
*/
public int size(){
return count;
}
/**
* Determines if a is equal to b
* #param a: generic type to test
* #param b: generic type to test
* #return boolean: true|false
*/
private boolean equalTo(T a, T b) {
return a.compareTo(b) == 0;
}
}
There is a problem with your moveToFront() method. It does not work for if node == first. If the node that needs to be moved is the first node, you end up setting first.next = first which is incorrect. The below code should work
public void moveToFront(DoubleNode node) {
DoubleNode previous = first;
temp = first;
while (temp != null && node != first) {
if (node.equals(temp.item)) {
//Found the item
previous.next = temp.next;
temp.next = first;
first = temp;
if (last.next != null) {
last = last.prev;
last.prev = previous;
}
return;
}
previous = temp;
temp = temp.next;
}
Now coming to moveToLast() the following code should work
public void moveToLast(DoubleNode node) {
DoubleNode temp = first;
DoubleNode prev = new DoubleNode(null); //dummy sentinel node
while (temp != null && node != last) {
if (temp == node) {
if (temp == first) first = temp.next;
prev.next = temp.next;
if (temp.next != null) temp.next.prev = prev;
last.next = temp;
temp.prev = last;
last = temp;
last.next = null;
break;
}
prev = temp;
temp = temp.next;
}
}

Created Linked List not returning correct index

I created a list that goes {50, 10, 60, 30, 40} and want to return the index when I reach 30 in my Linked List, however my program always returns -1 (basically it is unable to increment and return my index). I am not sure about how to go about getting back the index in a different manor unless I am able to cast the anEntry object into an integer and equal it my index.
class MyLinkedList {
private Node firstNode; // index = 0
private int length;
public MyLinkedList() {
firstNode = null;
length = 0;
} // end default constructor
/** Task: Adds a new entry to the end of the list.
* #param newEntry the object to be added as a new entry
* #return true if the addition is successful, or false if not */
public boolean add(Object newEntry) {
Node newNode = new Node(newEntry);
if (isEmpty())
firstNode = newNode;
else {
Node lastNode = getNode(length-1);
lastNode.next = newNode;
}
length++;
return true;
} // end add
/** Task: Adds a new entry at a specified index
* #param newEntry the object to be added at the specified index
* #return true if successful, or false if not */
public boolean add(int index, Object newEntry) {
boolean isSuccessful = true;
if ((index >= 0) && (index <= length)) {
Node newNode = new Node(newEntry);
if (isEmpty() || (index == 0)) {
newNode.next = firstNode;
firstNode = newNode;
}
else {
Node nodeBefore = getNode(index - 1);
Node nodeAfter = nodeBefore.next;
newNode.next = nodeAfter;
nodeBefore.next = newNode;
}
length++;
}
else
isSuccessful = false;
return isSuccessful;
} // end add
/** Task: Determines whether the list contains a given entry.
* #param anEntry the object that is the desired entry
* #return true if the list contains anEntry, or false if not */
public boolean contains(Object anEntry) {
boolean found = false;
Node currentNode = firstNode;
while (!found && (currentNode != null)) {
if (anEntry.equals(currentNode.data))
found = true;
else
currentNode = currentNode.next;
} // end while
return found;
} // end contains
/** Task: Gets an entry in the list.
* #param the desired index
* #return the desired entry, or
* null if either the list is empty or index is invalid */
public Object getEntry(int index) {
Object result = null; // result to return
if (!isEmpty() && (index >= 0) && (index < length))
result = getNode(index).data;
return result;
} // end getEntry
/** Task: Gets index of an entry in the list.
* #param the desired entry
* #return index of the first occurrence of the specified entry
* in this list, or -1 if this list does not contain the entry */
public int getIndex(Object anEntry) {
Node currentNode = firstNode;
int index = 0; // result to return
while (anEntry != currentNode.data) {
currentNode = currentNode.next;
index++;
if (anEntry.equals(currentNode.data)){
break;
}
else {
return -1;
}
}
return index;
} // end getIndex
private Node getNode(int index) {
Node currentNode = firstNode;
// traverse the list to locate the desired node
for (int counter = 0; counter < index; counter++)
currentNode = currentNode.next;
return currentNode;
} // end getNode
private Node getNode(int index) {
Node currentNode = firstNode;
// traverse the list to locate the desired node
for (int counter = 0; counter < index; counter++)
currentNode = currentNode.next;
return currentNode;
} // end getNode
private class Node {
private Object data; // data portion
private Node next; // link to next node
private Node(Object dataPortion) {
data = dataPortion;
next = null;
} // end constructor
private Node(Object dataPortion, Node nextNode) {
data = dataPortion;
next = nextNode;
} // end constructor
private void setData(Object dataPortion) {
data = dataPortion;
} // end setData
private Object getData() {
return data;
} // end getData
private void setNextNode(Node nextNode) {
next = nextNode;
} // end setNextNode
private Node getNextNode() {
return next;
} // end getNextNode
} // end Node
} // end MyLinkedList
The problem is that your while loop never does more than one iteration.
if (anEntry.equals(currentNode.data)){
break;
}
else {
return -1;
}
If the current element matches, then I have found the item so we can stop. If it doesn't, then the list does not contain this item. It should be relatively clear that this logic is wrong. Just because the current element doesn't match does not mean that subsequent elements might not match.
You can demonstrate this further by observing that getIndex(50) actually does return the correct index: zero. Your statement "my program always returns -1" is actually incorrect.
We need to swap this logic around - only return -1 after we have already tried all the elements.
while (anEntry != currentNode.data) {
currentNode = currentNode.next;
index++;
if (anEntry.equals(currentNode.data)){
return index;
}
}
return -1;
You will still have a problem where your code will throw an exception if the element is not in the list. This can be trivially solved with a minor change to the above code, but I'll leave that up to you to figure out!

Frequency Bag - getFrequencyOf(aData)

Having Trouble with the method getFrequencyOf(aData), returns zero for every element I am searching for in the Test code...here's my code if anyone can point me to what I'm doing wrong that would be much appreciated
public class FrequencyBag<T>
{
// TO DO: Instance Variables
private Node firstNode;
private int numberOfEntries;
/**
* Constructor
* Constructs an empty frequency bag.
*/
public FrequencyBag()
{
// TO DO
firstNode = null;
numberOfEntries = 0;
}
/**
* Adds new entry into this frequency bag.
* #param aData the data to be added into this frequency bag.
*/
public void add(T aData)
{
// TO DO
if(numberOfEntries != 0){
Node newNode = new Node(aData);
newNode.next = firstNode.next;
firstNode = newNode;
numberOfEntries++;
}
else{
Node newNode = new Node(aData);
firstNode = newNode;
}
}
/**
* Gets the number of occurrences of aData in this frequency bag.
* #param aData the data to be checked for its number of occurrences.
* #return the number of occurrences of aData in this frequency bag.
*/
public int getFrequencyOf(T aData)
{
// TO DO
int counter = 0;
Node currentNode = firstNode;
for(int i = 1; i <= numberOfEntries; i++)
{
if(currentNode.data.equals(aData))
{
counter++;
System.out.println(counter);
}
currentNode = currentNode.next;
}
System.out.println(counter);
return counter;
}
/**
* Gets the maximum number of occurrences in this frequency bag.
* #return the maximum number of occurrences of an entry in this
* frequency bag.
*/
public int getMaxFrequency()
{
// TO DO
Node currentNode = firstNode;
int currentFrequency = 0;
int maxFrequency = currentFrequency;
for(int i = 1; i <= numberOfEntries; i++)
{
currentFrequency = getFrequencyOf(currentNode.data);
if(currentFrequency > maxFrequency)
{
maxFrequency = currentFrequency;
}
currentNode = currentNode.next;
}
return maxFrequency;
}
/**
* Gets the probability of aData
* #param aData the specific data to get its probability.
* #return the probability of aData
*/
public double getProbabilityOf(T aData)
{
// TO DO
int num = getFrequencyOf(aData);
double probability = num / numberOfEntries;
return probability;
}
/**
* Empty this bag.
*/
public void clear()
{
// TO DO
firstNode.next = null;
firstNode.data = null;
}
/**
* Gets the number of entries in this bag.
* #return the number of entries in this bag.
*/
public int size()
{
// TO DO
return numberOfEntries;
}
private class Node
{
private T data;
private Node next;
public Node (T a)
{
data = a;
next = null;
}
public Node(T a, Node n)
{
data = a;
next = n;
}
}
}
To be honest, I did not read the full code, because there is a mistake in the add method, which probably causes the problem you face:
Node newNode = new Node(aData);
newNode.next = firstNode.next; //firstNode.next is null!
firstNode = newNode;
When you add the first node, it's pointing to a null node (its next value is null).
Then, when you add a second node, as in the line above, your new head of the list points to the next node of the previous head, which is always null. So, your list always has only one node, the firstNode. To fix that, change the above lines as:
Node newNode = new Node(aData);
newNode.next = firstNode;
firstNode = newNode;
OR (using the second constructor):
Node newNode = new Node(aData,firstNode);
firstNode = newNode;
This will make your new node the head of the linked list, having as its next element the previous head of the list.
UPDATE:
Also, another problem is that numberOfEntries is always 0, since you do not increment it when you add the very first node. So, add a numberOfEntries++; inside the else block of the add() method, or just move the one that exists in the if block, outside the block.

Sorted Linked List using comparable in Java

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

Categories