Trouble with accurately removing Nodes in a LinkedList - java

I wrote the following class for building a LinkedList with single values on top of a given code template.
.
.
public class LinkedElement<T> {
private T name;
private LinkedElement<T> link;
public LinkedElement(T value) {
this.name = value;
}
/**
* Returns the value of the i-th linked element, assuming the current element to
* be at index 0.
*
* #param i 0-based index of the element whose value to return.
* #return the i-th element's value, or {#code null} if there is no element with
* that index.
*/
public T get(int i) {
int iterator = i;
if (iterator == 0) {
return this.name;
}
if (this.link == null) {
iterator = 0;
return null;
}
if (iterator > 0) {
iterator = iterator - 1;
return this.link.get(iterator);
}
return null;
}
/**
* Adds a new linked element holding the given value at the end of the linked
* elements.
*
* #param newVal the new value.
*/
public void add(T newVal) {
if (this.link == null) {
this.link = new LinkedElement(newVal);
} else {
this.link.add(newVal);
}
}
**/**
* Removes the i-th element from the linked elements. If {#code i == 0}, this
* will effectively remove the head element. Thus, this method returns the
* linked element that is the new head element.
*
* #param i index of the element to remove.
* #return the new head element.
*/
public LinkedElement<T> remove(int i) {
// Store i as changeable iterator
int iterator = i;
// Store current head element;
LinkedElement<T> tempNode = this;
// If head element itself is to be removed
if (iterator == 0) {
if (this.link != null) {
this.name = this.link.name;
this.link = this.link.link;
}
if (this.link == null) {
this.name = null;
this.link = null;
}
return this;
// If the element is further down in the linkedlist
// iterate through list and invoke "remove" at the desired position inside
// the list
}
if (iterator > 0) {
iterator = iterator - 1;
return this.link.remove(iterator);
}
return null;**
}
}
The "remove" method seems to work fine when I remove just one element and print the elements out one by one. The trouble starts when I declare a new headElement through a remove method (which returns the new headElement in that respective list)
public static void main(String[] args) {
// An example
LinkedElement<String> headElement = new LinkedElement<String>("Yo!");
headElement.add("LA");
headElement.add("is");
headElement.add("about");
headElement.add("to");
headElement.add("witness");
headElement.add("another");
headElement.add("sunny");
headElement.add("day!");
System.out.println(headElement.get(7)); // prints "sunny"
headElement = headElement.remove(6); // removes "another"
headElement = headElement.remove(0); // removes "Yo!"
System.out.println(headElement.get(0)); // prints "sunny"
}
The expected output should be:
sunny
sunny
but I get
sunny
null
Question updated because I worded myself poorly.

because your headElement after remove(0) is:
LinkedElement<String> headElement = new LinkedElement<String>("what's");//0
headElement.add("up!");//1
headElement.add("That's");//2
headElement.add("Mitch");//3
headElement.add("Jones!");//4
and then you remove(2) from result above: which is "That's"; //at index 2
so yo get:
LinkedElement<String> headElement = new LinkedElement<String>("what's");//0
headElement.add("up!");//1
headElement.add("Mitch");//2
headElement.add("Jones!");//3
Try to print after remove(0) and you can get what is happening!

Try this:
public LinkedElement<T> remove(int i) {
int iterator = i;
// Store current head element;
LinkedElement<T> tempNode = this;
// If head element itself is to be removed
if (iterator == 0) {
if (tempNode.link != null) {
tempNode.name = tempNode.link.name;
tempNode.link = tempNode.link.link;
}
if (tempNode.link == null) {
tempNode.name = null;
tempNode.link = null;
}
return tempNode;
// If the element is further down in the linkedlist
// iterate through list and invoke "remove" at the desired position inside
// the list
}
if (iterator > 0) {
iterator = iterator - 2;
return tempNode.link.remove(iterator);
}
return tempNode;
}

Might try the following
public class LinkedElement<T> {
private T value;
private LinkedElement<T> linkToNextElement;
public LinkedElement(T element) {
value = element;
linkToNextElement = null;
}
public static void main(String args[]) {
LinkedElement<String> head = new LinkedElement("a");
head.add("b");
head.add("c");
head.add("d");
head.add("e");
LinkedElement<String> newHead = head;
for (int i = 0; i <= 6; i++) {
System.out.println("list[" + i + "]=" + head.get(i));
}
System.out.println("Head: value="+newHead.value+"\n");
System.out.println("###remove(1)###");
newHead = head.remove(1);
for (int i = 0; i <= 6; i++) {
System.out.println("list[" + i + "]=" + head.get(i));
}
System.out.println("Head: value="+newHead.value+"\n");
System.out.println("###remove(3)###");
newHead =head.remove(3);
for (int i = 0; i <= 6; i++) {
System.out.println("list[" + i + "]=" + head.get(i));
}
System.out.println("Head: value="+newHead.value+"\n");
System.out.println("###remove(0)###");
newHead =head.remove(0);
for (int i = 0; i <= 6; i++) {
System.out.println("list[" + i + "]=" + head.get(i));
}
System.out.println("Head: value="+newHead.value+"\n");
System.out.println("###remove(0)###");
newHead =head.remove(0);
for (int i = 0; i <= 6; i++) {
System.out.println("list[" + i + "]=" + head.get(i));
}
System.out.println("Head: value="+newHead.value+"\n");
System.out.println("###remove(i)###");
newHead =head.remove(7);
for (int i = 0; i <= 6; i++) {
System.out.println("list[" + i + "]=" + head.get(i));
}
System.out.println("Head: value="+newHead.value+"\n");
System.out.println("###remove(0)###");
newHead =head.remove(0);
for (int i = 0; i <= 6; i++) {
System.out.println("list[" + i + "]=" + head.get(i));
}
//empty List
if(newHead == null)
{
System.out.println("Head: value= NULL : no value for emplty list" );
}
}
/**
* Returns the value of the i-th linked element, assuming the current element to
* be at index 0.
*
* #param i 0-based index of the element whose value to return.
* #return the i-th element's value, or {#code null} if there is no element with
* that index.
*/
public T get(int i) {
int counter = 0;
LinkedElement<T> currElement = this;
if (i == 0) {
return value;
}
while (counter < i) {
if (currElement.linkToNextElement != null) {
currElement = currElement.linkToNextElement;
} else {
return null;
}
counter++;
}
return currElement.value;
}
/**
* Adds a new linked element holding the given value at the end of the linked
* elements.
*
* #param newVal the new value.
*/
public void add(T newVal) {
if (linkToNextElement == null) {
linkToNextElement = new LinkedElement<T>(newVal);
} else {
linkToNextElement.add(newVal);
}
}
/**
* Removes the i-th element from the linked elements. If {#code i == 0}, this
* will effectively remove the head element. Thus, this method returns the
* linked element that is the new head element.
*
* #param i index of the element to remove.
* #return the new head element.
*/
public LinkedElement<T> remove(int i) {
int counter = 0;
LinkedElement<T> currElement = this;
LinkedElement<T> prevElement = null;
LinkedElement<T> nextElement = null;
if (i == 0) {
if (currElement.linkToNextElement != null) {
nextElement = currElement.linkToNextElement;
value = nextElement.value;
if (nextElement.linkToNextElement != null) {
linkToNextElement = nextElement.linkToNextElement;
} else {
linkToNextElement = null;
}
// ;
return nextElement;
} else {
value = null;
linkToNextElement = null;
}
return linkToNextElement;
}
while (counter < i) {
if (currElement.linkToNextElement != null) {
prevElement = currElement;
currElement = currElement.linkToNextElement;
} else {
return this;
}
counter++;
}
if (currElement.linkToNextElement != null) {
nextElement = currElement.linkToNextElement;
prevElement.linkToNextElement = nextElement;
}
// last element
else {
prevElement.linkToNextElement = null;
}
return this;
}
}
Output
list[0]=a
list[1]=b
list[2]=c
list[3]=d
list[4]=e
list[5]=null
list[6]=null
Head: value=a
###remove(1)###
list[0]=a
list[1]=c
list[2]=d
list[3]=e
list[4]=null
list[5]=null
list[6]=null
Head: value=a
###remove(3)###
list[0]=a
list[1]=c
list[2]=d
list[3]=null
list[4]=null
list[5]=null
list[6]=null
Head: value=a
###remove(0)###
list[0]=c
list[1]=d
list[2]=null
list[3]=null
list[4]=null
list[5]=null
list[6]=null
Head: value=c
###remove(0)###
list[0]=d
list[1]=null
list[2]=null
list[3]=null
list[4]=null
list[5]=null
list[6]=null
Head: value=d
###remove(7)###
list[0]=d
list[1]=null
list[2]=null
list[3]=null
list[4]=null
list[5]=null
list[6]=null
Head: value=d
###remove(0)###
list[0]=null
list[1]=null
list[2]=null
list[3]=null
list[4]=null
list[5]=null
list[6]=null
Head: value= NULL : no value for empty list

Related

How can I fix my code to give the correct output instead of giving nothing?

When i run my code, i get nothing as my output. I suspect my code stops on this method:
public void deleteAt(int position)
{
if (position >= 0)
{
for (int i = position; i < theArray.length; i++)
{
theArray[i] = theArray[i + 1];
}
}
}
I think it stops at the above method because this code:
public int positionOf(char value)
{
//Search the list to find the value, if found return the position, if not, return -1
for (int i = 0; i < size(); i ++)
{
if (theArray[i] == value)
{
return i;
}
}
return -1;
}
only returns -1. If i remove the return -1; then Java thinks that there is an error because there is no return statment. I tried adding an else, but i still get the same error.
This is the whole code:
/** The interface for our List (Abstract Data Type) */
interface IList {
/** Adds the given value to the end of the list */
void append(char value);
/** Adds the given value to the beginning of the list */
void prepend(char value);
/** Deletes the container at the given position (a container holds a value) */
void deleteAt(int position);
/** Returns the number of values currently in our list */
int size();
/** Retrieves the value at the given position */
char getValueAt(int position);
/** Searches for the FIRST occurence of a given value in our list.
* If found, it returns the position of that value.
* If not found, it returns -1 */
int positionOf(char value);
}
/** Array implementation of our List */
class ListAsArray implements IList {
// initialize array to a size of 30 elements
// this will prevent the need to resize our array
char[] theArray = new char[30];
public void append(char value)
{
//Count until you find a place in the array that is empty, then insert
for (int i = 0; i < theArray.length; i ++)
{
if (theArray[i] == 0)
{
theArray[i] = value;
}
}
}
public void prepend(char value)
{
//Count until you find a empty value
for (int i = 0; i < theArray.length; i ++)
{
if (theArray[i] == 0)
{
//Once you find the empty value move everything over
for(int j = theArray.length; j != 0; j--)
{
theArray[i] = theArray[i + 1];
}
}
}
//Finally you want to actually add in the number in the first position
theArray[0] = value;
}
public void deleteAt(int position)
{
if (position >= 0)
{
for (int i = position; i < theArray.length; i++)
{
theArray[i] = theArray[i + 1];
}
}
}
public int size()
{
//Count until you find a place in the array that is empty, then return the number
int count = 0;
for (int i = 0; i < theArray.length; i ++)
{
if (theArray[i] == 0)
{
return count;
}
count ++;
}
return 0;
}
public char getValueAt(int position)
{
return theArray[position];
}
public int positionOf(char value)
{
//Search the list to find the value, if found return the position, if not, return -1
for (int i = 0; i < size(); i ++)
{
if (theArray[i] == value)
{
return i;
}
}
return -1;
}
}
/** Singly Linked List implementation of our List */
class ListAsLinkedList implements IList {
//Point to first node and second node
private Node head;
private Node tail;
//Constructor sets head and tail to null
public void LinkedList()
{
head = null;
tail = null;
}
public void append(char value)
{
//Wrap the data in a node
Node temp = new Node(value);
//Make this the first node if no other nodes
if (tail == null)
{
//Set tail to new node
tail = temp;
//Set head to new node
head = temp;
}
else
{
//Set new node to be after current end
tail.setNext(temp);
//Set as new tail
tail = temp;
}
}
public void prepend(char value)
{
//Wrap the data in a node
Node temp = new Node(value);
//Make this the first node if no other nodes
if (tail == null)
{
//Set tail to new node
tail = temp;
//Set head to new node
head = temp;
}
else
{
temp.next = head;
head = temp;
}
}
public void deleteAt(int position)
{
//Make the head node the next node if its the first one
if(position == 0)
{
head=head.next;
}
//If that wasn't the case...
Node current = head;
for(int i = 0; i < position-1; i++)
{
current = current.next;
}
current.next = current.next.next;
if(current.getNext() == null)
{
tail = current;
}
}
public int size()
{
Node temp = head;
for (int i = 0; i != 103; i++)
{
if (temp == tail)
{
return i;
}
}
return 0;
}
public char getValueAt(int position)
{
Node temp=head;
for(int i=0; i < position; i++)
{
temp=temp.next;
}
return temp.data;
}
public int positionOf(char value)
{
//Start at the beginning
int position = 0;
Node current = head;
//Look until we find target data
while (current.getData() != value)
{
//Move to next node
current = current.getNext();
//Increment position
position++;
}
//return position found
return position;
}
}
/** A singly linked list node for our singly linked list */
class Node {
//The node data and link to next node
public char data;
public Node next;
//Constructor
public Node(char data)
{
this.data = data;
this.next = null;
}
//Accessor
public char getData()
{
return data;
}
//Accessor
public Node getNext()
{
return next;
}
//Mutator
public void setData(char data)
{
this.data = data;
}
//Mutator
public void setNext(Node next)
{
this.next = next;
}
}
This is main:
/** contains our entry point */
public class Main {
/** entry point - DO NOT CHANGE the pre-existing code below */
public static void main(String[] args) {
int[] numbers = {105,116,112,115,65,58,47,47,116,105,110,121,88,117,114,108,46,99,111,109,47};
int[] numbers2 = {97,59,111,53,33,111,106,42,50};
int[] numbers3 = {116,104,32,111,116,32,111,71};
/// List as an Array
IList array = new ListAsArray();
// add values
for(int num : numbers) {
array.append((char)num);
}
for(int num : numbers3) {
array.prepend((char)num);
}
// delete some values
int position;
position = array.positionOf((char)105);
array.deleteAt(position);
position = array.positionOf((char)65);
array.deleteAt(position);
position = array.positionOf((char)88);
array.deleteAt(position);
// print em
position = 0;
while (position < array.size()) {
System.out.print(array.getValueAt(position));
position++;
}
/// List as a Linked List
IList linkedList = new ListAsLinkedList();
// add values
for(int num : numbers2) {
linkedList.append((char)num);
}
linkedList.prepend((char)55);
linkedList.prepend((char)121);
// delete some values
position = linkedList.positionOf((char)59);
linkedList.deleteAt(position);
position = linkedList.positionOf((char)33);
linkedList.deleteAt(position);
position = linkedList.positionOf((char)42);
linkedList.deleteAt(position);
// print em
position = 0;
while (position < linkedList.size()) {
System.out.print(linkedList.getValueAt(position));
position++;
}
System.out.println();
// ???
}
}
It should be outputting a link pertaining to the next part of my assignment.
The size() method always returns 0 according to your input.
size() method as per your code doesn't give you the length of the array to iterate over. Therefore you should use array length i.e theArray.length in positionOf() method's for loop instead of size() method.

Is there any thing wrong with my size() of the LinkedList?

I need help with my customized linked list, I couldn't figure out the problem. Need some Helps.
Here is my size() method:
public ObjectLinkedList() {
firstNode = null;
}
/**
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*
* Method: add() description: Insert an item into the list
*
* #param index position of the list
* #param obj the element is going to be inserted
* #author Jinyu Wu Date: 2017/2/4
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*/
#Override
public void add(int index, Object obj) {
Node tempNode = firstNode;
Node currentNode = new Node(obj);
if (index == 0) {
firstNode = currentNode;
return;
}
if (index < 0 || index > size()) {
System.out.println("add(ObjectLinkedList) index out of bound exception");
} else {
for (int i = 1; i <= index; i++) {
tempNode = tempNode.getNext();
if (i == index - 1) {
if (index != size() - 1) {
currentNode.setNext(tempNode.getNext());
} else {
currentNode.setNext(null);
}
tempNode.setNext(currentNode);
}
}
}
}
/**
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*
* Method: removeAt() description: remove an item from a position of the
* list
*
* #param index position in the list
* #author Jinyu Wu Date: 2017/2/4
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*/
#Override
public void removeAt(int index) {
if (index < 0 || index > size()) {
System.out.println("removeAt(ObjectLinkedList) index out of bound exception");
} else {
Node tempNode = firstNode;
if (index == 0) {
firstNode = firstNode.getNext();
} else {
for (int i = 1; i <= index; i++) {
if (i == index - 1) {
if (index != size() - 1) {
tempNode.setNext(tempNode.getNext().getNext());
} else {
tempNode.setNext(null);
}
}
tempNode = tempNode.getNext();
}
}
}
}
/**
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*
* Method: remove() description: remove a specific item from a position of
* the list
*
* #param obj target object is going to be removed
* #author Jinyu Wu Date: 2017/2/4
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*/
#Override
public void remove(Object obj) {
if (size() > 0) {
Node tempNode = firstNode;
for (int i = 0; i <= size(); i++) {
if (tempNode.equals(obj)) {
tempNode.setNext(tempNode.getNext().getNext());
break;
}
if (i < size() - 1) {
tempNode = tempNode.getNext();
}
}
System.out.println("target object is not found inside the linkedList(remove)");
}
}
/**
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*
* Method: get() description:get an item from the list
*
* #param index position in the list
* #author Jinyu Wu Date: 2017/2/4
* #return double ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*/
#Override
public Object get(int index) {
if (index < 0 || index > size()) {
System.out.println("get(ObjectLinkedList) index out of bound exception");
return null;
} else if (index == 0) {
return firstNode.getValue();
} else {
Node tempNode = firstNode;
for (int i = 0; i <= index; i++) {
if (i == index - 1) {
return tempNode.getValue();
}
tempNode = tempNode.getNext();
}
System.out.println("objectLinkedList get method nothing found");
return null;
}
}
/**
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*
* Method: toString() description: print out the content of the list
*
* #author Jinyu Wu Date: 2017/2/4
* #return Integer ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*/
#Override
public String toString() {
Node tmp = firstNode;
String res = "" + firstNode;
while (tmp.getNext() != null) {
tmp = tmp.getNext();
res += "," + tmp;
}
return "ObjectLinkedList{" + res + "}";
}
/**
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*
* Method: find() description:get an item from the list
*
* #author Jinyu Wu Date: 2017/2/4
* #param obj Object is going to be found
* #return Integer ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*/
#Override
public int find(Object obj) {
Node tempNode = firstNode;
if (obj.equals(firstNode.getValue())) {
return 0;
} else {
for (int i = 1; i < size(); i++) {
tempNode = tempNode.getNext();
if (tempNode.getValue().equals(obj)) {
return i;
}
}
return -1;
}
}
/**
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*
* Method: size() description:get the size of the list
*
* #author Jinyu Wu Date: 2017/2/4
* #return Integer ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*/
#Override
public int size() {
int size = 1;
if (firstNode == null) {
return 0;
}
try {
for (Node n = firstNode; n.getNext() != null; n = n.getNext()) {
size++;
}
return size;
} catch (NullPointerException e) {
return size;
}
}
Here is my Node class:
public class Node {
private Node nextNode;
private Object obj;
/**
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*
* Method: Node() description: constructor
*
* #author Jinyu Wu Date: 2017/2/4
* #param obj set the value
*/
public Node(Object obj) {
this.obj = obj;
this.nextNode = null;
}
/**
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*
* Method: getValue() description: get the value of object
*
* #author Jinyu Wu Date: 2017/2/4
* #return return the object
*/
public Object getValue() {
return this.obj;
}
/**
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*
* Method: setValue() description: setValue for the Node
*
* #author Jinyu Wu Date: 2017/2/4
* #param obj return the value
*/
public void setValue(Object obj) {
this.obj = obj;
}
/**
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*
* Method: getValue() description: get the next value of the currentNode
*
* #author Jinyu Wu Date: 2017/2/4
* #return return next node
*/
public Node getNext() {
if (nextNode != null) {
return this.nextNode;
} else {
return null;
}
}
/**
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*
* Method: setNext() description: set next value for the Node
*
* #author Jinyu Wu Date: 2017/2/4
* #param node set next node
*/
public void setNext(Node node) {
this.nextNode = node;
}
}
I kept getting wrong size number, but I couldn't figure out the problem.
Here is my code in the main method:
list = new ObjectLinkedList();
m1 = new Money(5, (byte) 6);
node1 = new Node(m1);
list.add(0, node1);
m2 = new Money(2, (byte) 4);
node2 = new Node(m2);
list.add(1, node2);
System.out.println(list.Size());
And I kept getting 1 instead of 2;
Add a size field to your ObjectLinkedList:
private int size;
Increment it in the line before you add a new item and decrement it in the line before you remove an item from your list.
Then just add a method:
public int getSize() {
return this.size;
}
Because of OP's request to post recursive method (this is inefficient!):
public int size(ObjectLinkedList list) {
if (list.firstNode == null)
return 0;
return 1 + size(list.firstNode.getNext());
}
Locating the error
The error resides in your add(int, Object) method, more precisely in the following construct:
for (int i = 1; i <= index; i++) {
tempNode = tempNode.getNext();
if (i == index - 1) {
if (index != size() - 1) {
currentNode.setNext(tempNode.getNext());
} else {
currentNode.setNext(null);
}
tempNode.setNext(currentNode);
}
}
The second time you add money to your list, you call list.add(1, node2). However, with index = 1 and i incremented starting at 1, i == index - 1 can never be true.
Hence, the second object is not inserted into your list at all. You can check this by calling your toString() method.
Finding a solution
I guess you do this if-clause, because you want the code nested inside execute only when tempNode is the one you are looking for. However, you can do this much more easily by putting the code 'behind' the for-loop and using its condition as follows:
for(int i = 1; i < index; i++) {
tempNode = tempNode.getNext();
}
if(index != size() - 1) {
currentNode.setNext(tempNode.getNext());
}
// we just created this node, so we can be quite sure that it does not have a next node set
// else {
// currentNode.setNext(null);
// }
tempNode.setNext(currentNode);
A side note
Your list already wraps objects in Nodes, so there's no need to do this in your main method. Hence, instead of
list = new ObjectLinkedList();
m1 = new Money(5, (byte) 6);
node1 = new Node(m1);
list.add(0, node1);
m2 = new Money(2, (byte) 4);
node2 = new Node(m2);
list.add(1, node2);
System.out.println(list.size());
you should be able to write
list = new ObjectLinkeList();
m1 = new Money(5, (byte) 6);
list.add(m1);
m2 = new Money(2, (byte) 4);
list.add(m2);
System.out.println(list.size());
or just
list = new ObjectLinkeList();
list.add(new Money(5, (byte) 6));
list.add(new Money(2, (byte) 4));
System.out.println(list.size());
Getting the size of a linked list is all about traversing it. Below I provide three options for traversing a linked list: a for loop, a while loop, and recursion.
class ObjectLinkedList<T> {
public static void main(String... args) {
final ObjectLinkedList<String> list = new ObjectLinkedList<>();
list.add(0, "World");
list.add(0, "Hello");
list.add(2, "!");
System.out.println(list);
System.out.println(list.size());
}
private Node<T> firstNode = null;
public void add(int index, T obj) {
final Node<T> newNode = new Node<>(obj);
Node<T> tempNode = firstNode;
if (index == 0) {
firstNode = newNode;
firstNode.setNext(tempNode);
return;
} else {
int count = 0;
//option 1: a for loop
for (Node<T> current = firstNode; current != null; current = current.getNext()) {
tempNode = current.getNext();
if (++count == index) {
current.setNext(newNode);
newNode.setNext(tempNode);
return;
}
}
}
throw new IndexOutOfBoundsException("Out of bounds!");
}
public String toString() {
Node<T> tmp = firstNode;
StringBuilder res = new StringBuilder("ObjectLinkedList: [");
//option 2: a while loop
while (tmp != null) {
res.append(tmp);
tmp = tmp.getNext();
if (tmp != null) {
res.append(", ");
}
}
return res.append("]").toString();
}
public int size() {
return distanceFromEnd(firstNode);
}
//option 3: recursion
private int distanceFromEnd(Node<T> startingNode) {
if (startingNode == null) {
return 0;
} else {
return 1 + distanceFromEnd(startingNode.getNext());
}
}
}
class Node<T> {
private Node<T> next = null;
final private T value;
public Node(final T value) {
assert value != null;
this.value = value;
}
public Node<T> getNext() {
return next;
}
public void setNext(final Node<T> next) {
this.next = next;
}
public T getValue() {
return value;
}
#Override
public String toString() {
return value.toString();
}
}

How do I remove the first node in a linked list with a remove method

I want to create a linked list then populate it with 1-100. After that I print out all the even numbers without actually removing the odd numbers from the list, then print out the even numbers again, but double them. After these things, I remove the odd numbers from the linked list and print out the list. The last step that I have mentioned is where I am hung up. Everything else works fine, just my remove method removes all the odd numbers except 1. In my main method I use an if statement that says if the number contained in the node % 2 equals zero, remove the node. It works for every node except the first one. Thank you guys for any help you can give me. My code follows.
import java.util.*;
/*
* My ListNode class
*/
class ListNode<Integer> {
private Integer item;
private ListNode<Integer> next;
public ListNode(Integer item) {
this.item = item;
next = null;
}
public ListNode(Integer item, ListNode<Integer> next) {
this.item = item;
this.next = next;
}
public Integer getItem() {
return item;
}
public ListNode<Integer> getNext() {
return next;
}
public void setItem(Integer item) {
this.item = item;
}
public void setNext(ListNode<Integer> next) {
this.next = next;
}
}
/*
* My LinkedList class
*/
class LinkedList<Integer> {
public ListNode<Integer> front;
public LinkedList() {
front = null;
}
public boolean isEmpty() {
return front == null;
}
public boolean contains(int target) {
for (ListNode<Integer> node = front;
node != null;
node = node.getNext()) {
if (node.getItem().equals(target)) {
return true;
}
}
return false;
}
public int size() {
int count = 0;
for (ListNode<Integer> node = front;
node != null;
node = node.getNext()) {
count++;
}
return count;
}
public String toString() {
String result = "( ";
for (ListNode<Integer> node = front;
node != null;
node = node.getNext()) {
result += node.getItem() + " ";
}
return result + ")";
}
public Integer get(int index) {
ListNode<Integer> node = front;
for (int i = 0; i < index; i++) {
node = node.getNext();
}
return node.getItem();
}
public void set(int index, Integer target) {
ListNode<Integer> node = front;
for (int i = 0; i < index; i++) {
node = node.getNext();
}
node.setItem(target);
}
public void add(int index, int target) {
if (isEmpty()) {
front = new ListNode(target);
} else {
ListNode last = front;
while (last.getNext() != null) {
last = last.getNext();
}
last.setNext(new ListNode(target));
}
}
public Integer remove(int index) {
ListNode<Integer> node = front;
ListNode<Integer> prev = front;
for (int i = 0; i < index; i++) {
prev = node;
node = node.getNext();
}
prev.setNext(node.getNext());
return node.getItem();
}
}
public class LinkedListTest {
//interface Removal {
//Integer remove (Integer item);
//}
public static void main(String[] args) {
LinkedList<Integer> list = new LinkedList<Integer>();
System.out.println(list);
System.out.println("The list size is " + list.size());
System.out.println();
/*
* This adds the numbers 1 through 100 to a LinkedList
*/
for (int i = 1; i <= 100; i++)
list.add(0, i);
System.out.println(list);
System.out.println("The list size is " + list.size());
System.out.println();
/*
* This prints out only even numbers by excluding indexes that are even,
* because all the even numbers are held in the odd numbered indexes, thus
* index 0 is 1 but index 1 is 2, index 3 is 4
*/
for (int i = 0; i < list.size(); i++)
if (i % 2 == 1) {
System.out.print(list.get(i) + " ");
}
System.out.println();
System.out.println("The list size is " + list.size());
System.out.println();
/*
* This doubles even numbers
*/
for (int i = 0; i < list.size(); i++)
if (i % 2 == 1) {
int result = list.get(i) * 2;
System.out.print(result + " ");
}
System.out.println();
System.out.println("The list size is " + list.size());
System.out.println();
for (int i = 0; i < list.size(); i++)
if (list.get(i) % 2 == 1) {
list.remove(i);
}
System.out.print(list);
System.out.println();
System.out.println("The list size is " + list.size());
System.out.println();
/*
* These contain methods only work for the first list created
*/
System.out.println("Does the list contain 32? " + list.contains(32));
System.out.println("Does the list contain 33? " + list.contains(33));
}
}
Your remove method doesn't actually work when value of index is 0.. Because both your node and prev are initialized to front and the loop is not being executed because the i<index condition is false. So you have to add another condition for the case of index=0
Adding these lines at the starting of your remove method solves the problem..
if(index==0){
ListNode<integer>temp=front;
front=front.getNext();
return temp.getItem();
}
hope it helped...

Initialize an Item Array

I want to initialize an Item Array but can't figure it out.
Here is my code.
public class HashTable<Item> {
private int m; // hash table size
private Item[] T; // hash table
HashTable(int M)
{
m = M;
T = new Item[M];
for(int i=0;i<M;i++){
Item T[i] = null;
}
}
...
...
SOLUTION
T = (Item[])new Object[M];
I think what you need is something like:
for(int i=0;i<M;i++){
T[i] = new Item(); // call some constructor here
}
You have
Item T[i] = ...
in your loop, while it should be just
T[i] = ...
So try these hints.
Also do this:
T = (Item[])new Object[M];
as Kumar suggested in his reply.
The thing is that Item is not really a type here. You need
to read how generics are actually compiled into bytecode,
and you will see what happens under the hood.
You are trying to create the array of Generic type,Please look at this post.
How to create a generic array in Java?
Assuming you created the class item you could call it like this:
public class HashTable
{
private int tableSize; // hash table size
private Item[] table; // hash table
public static void main(String[] args)
{
// where 10 is the number of nodes
Item[] myTable = createHashTable(10);
}
private static Item[] createHashTable(int size)
{
Item[] table = new Item[size];
for(int i = 0; i < table.length; i++)
{
table[i] = new Item(i);
}
}
}
However if you want to see an example of a full HashTable implementation:
/*
* HashTable.java
*
*
*/
/**
* A class that implements a hash table that employs open addressing
* using either linear probing, quadratic probing, or double hashing.
*/
public class HashTable {
/* Private inner class for an entry in the hash table */
private class Entry {
private String key;
private LLList valueList; // all of the values with this key
private boolean hasBeenRemoved; // has this entry been removed?
private Entry(String key, int value) {
this.key = key;
valueList = new LLList();
valueList.addItem(value, 0);
hasBeenRemoved = false;
}
}
// parameters for the second hash function -- see h2() below
private static final int H2_MIN = 5;
private static final int H2_DIVISOR = 11;
// possible types of probing
public static final int LINEAR = 0;
public static final int QUADRATIC = 1;
public static final int DOUBLE_HASHING = 2;
public static final int NUM_PROBE_TYPES = 3;
private Entry[] table; // the hash table itself
private int probeType = LINEAR; // the type of probing
// keeps track of how many times we perform a probe of a given length
private int[] probeLengthCount;
public HashTable(int size, int probeType) {
if (probeType >= 0 && probeType < NUM_PROBE_TYPES)
this.probeType = probeType;
else
throw new IllegalArgumentException("invalid probeType: " +
probeType);
table = new Entry[size];
probeLengthCount = new int[size + 1];
for (int i = 0; i <= size; i++)
probeLengthCount[i] = 0;
}
public HashTable(int size) {
// Call the other constructor to do the work.
this(size, LINEAR);
}
/* first hash function */
private int h1(String key) {
int h1 = key.hashCode() % table.length;
if (h1 < 0)
h1 += table.length;
return h1;
}
/* second hash function */
private int h2(String key) {
int h2 = key.hashCode() % H2_DIVISOR;
if (h2 < 0)
h2 += H2_DIVISOR;
h2 += H2_MIN;
return h2;
}
/*
* probeIncrement - returns the amount by which the current index
* should be incremented to obtain the nth element in the probe
* sequence
*/
private int probeIncrement(int n, int h2) {
if (n <= 0)
return 0;
switch (probeType) {
case LINEAR:
return 1;
case QUADRATIC:
return (2*n - 1);
case DOUBLE_HASHING:
default:
return h2;
}
}
/*
* probe - attempt to find a slot in the hash table for the specified key.
*
* If key is currently in the table, it returns the index of the entry.
* If key isn't in the table, it returns the index of the first empty cell
* in the table.
* If overflow occurs, it returns -1.
*/
private int probe(String key) {
int i = h1(key); // first hash function
int h2 = h2(key); // second hash function
int positionsChecked = 1;
// keep probing until we get an empty position or a match
while (table[i] != null && !key.equals(table[i].key)) {
if (positionsChecked == table.length) {
probeLengthCount[positionsChecked]++;
return -1;
}
i = (i + probeIncrement(positionsChecked, h2)) % table.length;
positionsChecked++;
}
probeLengthCount[positionsChecked]++;
return i;
}
/**
* insert - insert the specified (key, value) pair in the hash table
*/
public void insert(String key, int value) {
if (key == null)
throw new IllegalArgumentException("key must be non-null");
int i = h1(key);
int h2 = h2(key);
int positionsChecked = 1;
int firstRemoved = -1;
while (table[i] != null && !key.equals(table[i].key)) {
if (table[i].hasBeenRemoved && firstRemoved == -1)
firstRemoved = i;
if (positionsChecked == table.length)
break;
i = (i + probeIncrement(positionsChecked, h2)) % table.length;
positionsChecked++;
}
probeLengthCount[positionsChecked]++;
if (table[i] != null && key.equals(table[i].key))
table[i].valueList.addItem(value, 0);
else if (firstRemoved != -1)
table[firstRemoved] = new Entry(key, value);
else if (table[i] == null)
table[i] = new Entry(key, value);
else
throw new RuntimeException("overflow occurred");
}
/**
* search - search for the specified key, and return the
* associated list of values, or null if the key is not in the
* table
*/
public LLList search(String key) {
if (key == null)
throw new IllegalArgumentException("key must be non-null");
int i = probe(key);
if (i == -1 || table[i] == null)
return null;
else
return table[i].valueList;
}
/**
* remove - remove from the table the entry for the specified key
*/
public void remove(String key) {
if (key == null)
throw new IllegalArgumentException("key must be non-null");
int i = probe(key);
if (i == -1 || table[i] == null)
return;
table[i].key = null;
table[i].valueList = null;
table[i].hasBeenRemoved = true;
}
/**
* printStats - print the statistics for the table -- i.e., the
* number of keys and items, and stats for the number of times
* that probes of different lengths were performed
*/
public void printStats() {
int numProbes = 0;
int probeLengthSum = 0;
int numKeys = 0;
for (int i = 0; i < table.length; i++) {
if (table[i] != null && !table[i].hasBeenRemoved)
numKeys++;
}
System.out.println("\n" + numKeys + " keys");
System.out.println("probe-length stats:");
System.out.println("length\tcount");
for (int i = 1; i <= table.length; i++) {
if (probeLengthCount[i] != 0)
System.out.println(i + "\t" + probeLengthCount[i]);
numProbes += probeLengthCount[i];
probeLengthSum += (probeLengthCount[i] * i);
}
System.out.println("average probe length = " +
(double)probeLengthSum / numProbes);
}
}
Here is the second file for a Linked-Linked-List
/*
* LLList.java
*
*
*/
import java.util.*;
/**
* A class that implements our simple List interface using a linked list.
* The linked list includes a dummy head node that allows us to avoid
* special cases for insertion and deletion at the front of the list.
*/
public class LLList implements List {
// Inner class for a node. We use an inner class so that the LLList
// methods can access the instance variables of the nodes.
private class Node {
private Object item;
private Node next;
private Node(Object i, Node n) {
item = i;
next = n;
}
}
private Node head; // dummy head node
private int length; // # of items in the list
/**
* Constructs a LLList object for a list that is initially empty.
*/
public LLList() {
head = new Node(null, null);
length = 0;
}
/*
* getNode - private helper method that returns a reference to the
* ith node in the linked list. It assumes that the value of the
* parameter is valid.
*
* If i == -1, it returns a reference to the dummy head node.
*/
private Node getNode(int i) {
Node trav = head;
int travIndex = -1;
while (travIndex < i) {
travIndex++;
trav = trav.next;
}
return trav;
}
/** getItem - returns the item at position i in the list */
public Object getItem(int i) {
if (i < 0 || i >= length)
throw new IndexOutOfBoundsException();
Node n = getNode(i);
return n.item;
}
/**
* addItem - adds the specified item at position i in the list,
* shifting the items that are currently in positions i, i+1, i+2,
* etc. to the right by one. Always returns true, because the list
* is never full.
*
* We don't need a special case for insertion at the front of the
* list (i == 0), because getNode(0 - 1) will return the dummy
* head node, and the rest of insertion can proceed as usual.
*/
public boolean addItem(Object item, int i) {
if (i < 0 || i > length)
throw new IndexOutOfBoundsException();
Node newNode = new Node(item, null);
Node prevNode = getNode(i - 1);
newNode.next = prevNode.next;
prevNode.next = newNode;
length++;
return true;
}
/**
* removeItem - removes the item at position i in the list,
* shifting the items that are currently in positions i+1, i+2,
* etc. to the left by one. Returns a reference to the removed
* object.
*
* Here again, we don't need a special case for i == 0 (see the
* note accompanying addItem above).
*/
public Object removeItem(int i) {
if (i < 0 || i >= length)
throw new IndexOutOfBoundsException();
Node prevNode = getNode(i - 1);
Object removed = prevNode.next.item;
prevNode.next = prevNode.next.next;
length--;
return removed;
}
/** length - returns the number of items in the list */
public int length() {
return length;
}
/**
* isFull - always returns false, because the linked list can
* grow indefinitely and thus the list is never full.
*/
public boolean isFull() {
return false;
}
/**
* toString - converts the list into a String of the form
* [ item0 item1 ... ]
*/
public String toString() {
String str = "[ ";
Node trav = head.next; // skip over the dummy head node
while (trav != null) {
str += (trav.item + " ");
trav = trav.next;
}
str += "]";
return str;
}
/**
* iterator - returns an iterator for this list
*/
public ListIterator iterator() {
return new LLListIterator();
}
/*
*** private inner class for an iterator over an LLList ***
*/
private class LLListIterator implements ListIterator {
private Node nextNode; // the next node to visit
private Node lastVisitedNode; // the most recently visited node
public LLListIterator() {
nextNode = head.next;
lastVisitedNode = null;
}
/**
* hasNext - does the iterator have additional items to visit?
*/
public boolean hasNext() {
return (nextNode != null);
}
/**
* next - returns a reference to the next Object in the iteration
*/
public Object next() {
if (nextNode == null)
throw new NoSuchElementException();
Object item = nextNode.item;
lastVisitedNode = nextNode;
nextNode = nextNode.next;
return item;
}
}
}

nullpointer exception caused with queue

i believe the error is caused by incorrect adding to the queue and there might be other errors but i think it is something here
public void add(E data)
{
if(size == 0)
{
size++;
front = new ListNode(data,null);
}
else
{
size++;
ListNode <E> temp = end;
temp.setNext(null);
temp = temp.getNext();
temp.setData(data);
end = temp;
}
}
if you need the rest of the code to find the error here is the full class
import java.util.*;
public class Queue<E>
{
private ListNode <E> front;
private ListNode <E> end;
private int size;
public Queue()
{
front = null;
end = null;
size = 0;
}
public E peek()
{
return front.getData();
}
public E remove()
{
if(size == 0){return null;}
else
{
ListNode <E> temp = front;
front = temp.getNext();
size--;
return temp.getData();
}
}
public void add(E data)
{
if(size == 0)
{
size++;
front = new ListNode(data,null);
}
else
{
size++;
ListNode <E> temp = end;
temp.setNext(null);
temp = temp.getNext();
temp.setData(data);
end = temp;
}
}
public boolean isEmpty()
{
if (size == 0)
return true;
else
return false;
}
// [data, data, data, data]
public String toString()
{
String s ="";
ListNode <E> temp = front;
while(temp.getNext()!= null)
{
s+=temp.getData() + ", ";
}
return s;
}
public int size()
{
return size;
}
}
and here is the node i'm using
public class ListNode<E>
{
private E data;
private ListNode<E> next;
/**
* Constructs a ListNode with a specified data and next
* #param d the data for the node
* #param n the next reference
*/
public ListNode(E d, ListNode<E> n)
{
data = d;
n = next;
}
/**
* returns the data from the node
* #return the data field
*/
public E getData() {return data;}
/**
* sets the data for the node
* #param d the new data field
*/
public void setData(E d) {data = d;}
/**
* gets the next reference of the node
* #return the next reference
*/
public ListNode<E> getNext() { return next; }
/**
* sets the next reference for the node
* #param n the new next reference
*/
public void setNext(ListNode<E> n) { next = n;}
}
and this is what i am using to test it
public class QueueTester
{
public static void main (String args[])
{
Queue<Integer> queue = new Queue<Integer>();
for (int k = 1; k <= 100; k++) // add 1 to 100
queue.add(k);
System.out.println ("Size: " + queue.size());
System.out.println(queue + "\n");
for (int k = 1; k <= 50; k++) // remove 1 to 50, contents 51 to 100
{
int number = queue.remove();
}
System.out.println ("Size: " + queue.size());
System.out.println(queue + "\n");
for (int k = 200; k <= 500; k+=10) // add tens 200 to 500 (after 51 to 100)
queue.add(k);
System.out.println ("Size: " + queue.size());
System.out.println(queue + "\n");
while (!queue.isEmpty()) // prints contents (should be 51 to 100, then 200 to 500 tens)
{
System.out.print(queue.remove() + " ");
}
System.out.println("\n");
System.out.println ("Size: " + queue.size());
System.out.println(queue); // empty
System.out.println ("Remove from empty queue: " + queue.remove() + "\n") ;
}
}
try this..
if(size == 0)
{
front = new ListNode(data,null);
end = first;
size++;
}
else
{
ListNode <E> temp = new ListNode(data);
end.setNext(temp);
end = end.getNext();
size++;
}
Your add method is not implemented correctly and will always just change the front.
When you call eventually call remove()
public E remove()
{
if(size == 0){return null;}
else
{
ListNode <E> temp = front;
front = temp.getNext();
size--;
return temp.getData();
}
}
since size == 0, you will return null. You then try to dereference null into an int
int number = queue.remove();
This will throw a NullPointerException.
Review your logic, if you add something to the list, you should probably increment the size.
Also, note that in your add() method
ListNode <E> temp = end;
temp.setNext(null);
will also fail since end is originally null.

Categories