So I am working on a project involving Linked Lists. We have to make the Nodes and the Linked Lists ourselves (not allowed to use the Java provided ones). As part of the project, I am making a list that will automatically adjust itself upon certain criteria (when the word being entered is the same as one that already exists, move that Node to the front of the list). My code appears to run fine but after a certain amount of time, it just stops running. When I try debugging it, Eclipse just suspends the process at that point and I cannot figure out why as it provides absolutely no feedback at all. It appears to be on one of the while loops but I can't seem to figure out why. Any help would be greatly appreciated. The code is relatively long so I will paste it below this wall of text. I am not super experienced in programming yet so you might notice some mistakes/annoyances.
SelfAdjustingListOne.java
public class SelfAdjustingListOne extends UnsortedList
{
public SelfAdjustingListOne()
{
super();
}
public SelfAdjustingListOne(long timer)
{
super(timer);
}
public void adjustingAdd(Node input)
{
// If there's nothing in the list, make this the first and last node
if (getFront() == null)
{
setFront(input);
setBack(input);
input.setIndex(0);
} else if (sameWord(input) != null)
{
// If the word already exists, increment the word count and send that node to
// the front of the list
Node sameString = sameWord(input), current = getFront(), previous;
try
{
// Will return null if sameString is the first node on the list
previous = getByIndex(sameString.getIndex() - 1);
} catch (NullPointerException e)
{
previous = null;
}
// If sameString is the first node, no link needs to be set
if (previous != null)
previous.setLink(sameString.getLink());
// Link the node we are moving to the front node
sameString.setLink(getFront());
// Set the value of the front node to the node we are moving
setFront(sameString);
// Increment its count
sameString.plusCount();
// While the current node exists and has not surpassed the previous location of
// the node we moved, increment the index value of each node by 1
while (current != null && current.getIndex() != sameString.getIndex())
{
current.plusIndex();
current = current.getLink();
}
// Set the new front node's index to 0 (Beginning of the list)
sameString.setIndex(0);
plusComparisons();
plusComparisons();
} else
{
// If the list has at least one node and the word being added doesn't exist, add
// this node to the front of the list
input.setLink(getFront());
Node current = getFront();
while (current != null)
{
current.plusIndex();
current = current.getLink();
}
setFront(input);
input.setIndex(0);
plusComparisons();
plusNodeChanges();
plusNodeChanges();
}
}
}
UnsortedList.java
import java.text.DecimalFormat;
public class UnsortedList
{
private Node front;
private Node back;
private Long timer;
private int numOfComparisons;
private int nodeChanges;
public UnsortedList()
{
}
public UnsortedList(long timer)
{
this.timer = timer;
}
public void addBack(Node input)
{
if (front == null)
{
setFront(input);
setBack(input);
input.setIndex(0);
} else if (sameWord(input) != null)
{
Node sameString = sameWord(input);
sameString.plusCount();
numOfComparisons += 2;
} else
{
getBack().setLink(input);
input.setIndex(back.getIndex() + 1);
setBack(input);
numOfComparisons++;
nodeChanges += 2;
}
}
public void addFront(Node input)
{
if (front == null)
{
setFront(input);
setBack(input);
input.setIndex(0);
} else if (sameWord(input) != null)
{
Node sameString = sameWord(input);
sameString.plusCount();
numOfComparisons += 2;
} else
{
input.setLink(front);
Node current = front;
while (current != null)
{
current.plusIndex();
current = current.getLink();
}
setFront(input);
input.setIndex(0);
numOfComparisons++;
nodeChanges += 2;
}
}
public void remove(int index)
{
Node current = front;
do
{
if (current.getIndex() == index - 1)
{
if (current.getLink().getLink() != null)
{
current.getLink().setIndex(-1);
current.setLink(current.getLink().getLink());
Node currentIndexNode = current.getLink();
while (currentIndexNode != null)
{
currentIndexNode.minusIndex();
currentIndexNode = currentIndexNode.getLink();
}
} else
{
current.getLink().setIndex(-1);
current.setLink(null);
}
}
current = current.getLink();
} while (!current.isEqual(back));
}
public void setFront(Node input)
{
front = input;
}
public void setBack(Node input)
{
back = input;
}
public Node getFront()
{
return front;
}
public Node getBack()
{
return back;
}
public Node getByIndex(int index) throws NullPointerException
{
Node current = front, currentIndexNode = current.getLink();
while (current != null)
{
do
{
if (current.getIndex() == index)
return current;
current = currentIndexNode;
currentIndexNode = currentIndexNode.getLink();
} while (currentIndexNode != null);
}
return null;
}
public Node getByWord(String word) throws NullPointerException
{
Node current = front, currentIndexNode = current.getLink();
while (current != null)
{
do
{
if (current.getWord().equalsIgnoreCase(word))
return current;
current = currentIndexNode;
currentIndexNode = currentIndexNode.getLink();
} while (currentIndexNode != null);
}
return null;
}
public int totalWords()
{
Node current = front;
int totalWords = 0;
while (current != null)
{
totalWords += current.getCount();
current = current.getLink();
}
return totalWords;
}
public int totalUniqueWords()
{
Node current = front;
int totalUniqueWords = 0;
while (current != null)
{
totalUniqueWords++;
current = current.getLink();
}
return totalUniqueWords;
}
public int totalNumOfComparisons()
{
return numOfComparisons;
}
public int totalNodeChanges()
{
return nodeChanges;
}
public String totalTimeElapsed()
{
if (timer == null)
return "This is an untimed list";
DecimalFormat threePlaces = new DecimalFormat("#0.000");
return threePlaces.format((System.nanoTime() - timer) * Math.pow(10, -9)) + " seconds";
}
public void plusComparisons()
{
numOfComparisons++;
}
public void plusNodeChanges()
{
nodeChanges++;
}
protected Node sameWord(Node input)
{
Node current = front;
while (current != null)
{
if (current.getWord().equalsIgnoreCase(input.getWord()))
return current;
current = current.getLink();
}
return null;
}
}
Node.java
public class Node
{
private Node link;
private String word;
private int count = 1;
private int index = -1;
public Node(String word)
{
this.word = word;
}
public Node getLink()
{
return link;
}
public String getWord()
{
return word;
}
public int getCount()
{
return count;
}
public int getIndex()
{
return index;
}
public void setLink(Node input)
{
link = input;
}
public void setWord(String input)
{
word = input;
}
public void setCount(int input)
{
count = input;
}
public void setIndex(int input)
{
index = input;
}
public void plusCount()
{
count++;
}
public void plusIndex()
{
index++;
}
public void minusIndex()
{
index--;
}
public boolean isEqual(Node input)
{
if (input.getWord().equalsIgnoreCase(this.word))
return true;
return false;
}
}
The code which runs the SelfAdjustingListOne
public static SelfAdjustingListOne salo;
public static void main(String[] args)
{
System.out.println("Running fifth pass...");
System.out.println("Time to execute fifth pass: " + pass5());
}
public static String pass5()
{
salo = new SelfAdjustingListOne(System.nanoTime());
try
{
Scanner scanner = new Scanner(new File(fileDirectory + fileNames[0] + fileExtension));
while (scanner.hasNext())
{
String s = scanner.next();
s.replaceAll("^[^a-zA-Z0-9]+", "");
s.replaceAll("[^a-zA-Z0-9]+$", "");
if (s.length() == 1 || s.length() == 0)
{
if (!Character.isAlphabetic(s.charAt(0)) && !Character.isDigit(s.charAt(0)))
continue;
}
salo.adjustingAdd(new Node(s));
}
scanner.close();
} catch (FileNotFoundException e)
{
System.out.println("No file found matching that name/directory");
}
return salo.totalTimeElapsed();
}
The file it says it's reading in is the A Bee Movie Script which I cannot post because of the max length of a post but any text file should do.
I figured it out with a little help from samabcde.
This block of code right here needed to be changed from this:
if (previous != null)
previous.setLink(sameString.getLink());
// Link the node we are moving to the front node
sameString.setLink(getFront());
// Set the value of the front node to the node we are moving
setFront(sameString);
To this:
if(sameString != getFront())
{
sameString.setLink(getFront());
// Set the value of the front node to the node we are moving
setFront(sameString);
}
It was linking to itself because it never checked to see if the node it was setting the link of WAS ALREADY the first node in the list, therefore setting the link equal to itself.
Related
I trying and need help on how to create a private method to search a singly linked list.
My private search method is all the way at the bottom, how can I create a private method so i can then use it in an add/delete method?
I have been trying to do this for hours and I can't seem to get it right, i want to make a private search method to avoid loops later on in my other methods such as find add delete
public class LinkedBag<T> {
private Node first;
private int n;
public LinkedBag() {
}
public boolean isEmpty() {
return first == null;
}
public int size() {
return n;
}
public void add(T item) {
Node oldfirst = first;
first = new Node();
first.item = item;
first.next = oldfirst;
n++;
}
public int search(T item) {
if(item == null) {
throw new IllegalArgumentException("Cannot search null");
}
Node x = first;
int c = size() - 1;
while(x != null) {
if(x.item.equals(item)) {
return c;
}
x = x.next;
c--;
}
return -1;
}
private class Node {
private T item;
private Node next;
}
public static void main(String[] args) {
LinkedBag<Integer> intBag = new LinkedBag<>();
intBag.add(1);
intBag.add(2);
intBag.add(3);
System.out.println(intBag.search(1) == 0);
System.out.println(intBag.search(2) == 1);
System.out.println(intBag.search(3) == 2);
System.out.println(intBag.search(4) == -1);
}
}
You can create a search method in a single linked list which returns the position of the item or e.g. -1 in case the item was not found.
This search method will need to loop from the first node through its tailing nodes sequentially, extracts the item associated to each node and uses the equals method to try to find a match with the search item.
Here is a possible implementation in Java:
public int search(T item) {
Node x = first;
int c = size() - 1;
while(x != null) {
if(x.item.equals(item)) {
return c;
}
x = x.next;
c--;
}
return -1;
}
Below is a full example of how you can do it in a simple linked list with minimal generics support. Included is also a main method with a minimal unit test to prove the concept:
public class LinkedBag<T> {
private Node first;
private int n;
public LinkedBag() {
}
public boolean isEmpty() {
return first == null;
}
public int size() {
return n;
}
public void add(T item) {
Node oldfirst = first;
first = new Node();
first.item = item;
first.next = oldfirst;
n++;
}
public int search(T item) {
if(item == null) {
throw new IllegalArgumentException("Cannot search null");
}
Node x = first;
int c = size() - 1;
while(x != null) {
if(x.item.equals(item)) {
return c;
}
x = x.next;
c--;
}
return -1;
}
private class Node {
private T item;
private Node next;
}
public static void main(String[] args) {
LinkedBag<Integer> intBag = new LinkedBag<>();
intBag.add(1);
intBag.add(2);
intBag.add(3);
System.out.println(intBag.search(1) == 0);
System.out.println(intBag.search(2) == 1);
System.out.println(intBag.search(3) == 2);
System.out.println(intBag.search(4) == -1);
}
}
This is for a class assignment; I currently have a single-linked list and need to convert it into a doubly-linked list. Currently, the list is a collection of historical battles.
What in this program needs to be changed to turn this into a double-linked list? I feel like I'm really close, but stuck on a certain part (What needs to be changed in the 'add' part)
public static MyHistoryList HistoryList;
public static void main(String[] args) {
//Proof of concept
HistoryList = new MyHistoryList();
HistoryList.add("Battle of Vienna");
HistoryList.add("Spanish Armada");
HistoryList.add("Poltava");
HistoryList.add("Hastings");
HistoryList.add("Waterloo");
System.out.println("List to begin with: " + HistoryList);
HistoryList.insert("Siege of Constantinople", 0);
HistoryList.insert("Manzikert", 1);
System.out.println("List following the insertion of new elements: " + HistoryList);
HistoryList.remove(1);
HistoryList.remove(2);
HistoryList.remove(3);
System.out.println("List after deleting three things " + HistoryList);
}
}
class MyHistoryList {
//setting up a few variables that will be needed
private static int counter;
private Node head;
This is the private class for the node, including some getters and setters. I've already set up 'previous', which is supposed to be used in the implementation of the doubly-linked list according to what I've already googled, but I'm not sure how to move forward with the way MY single-list is set up.
private class Node {
Node next;
Node previous;
Object data;
public Node(Object dataValue) {
next = null;
previous = null;
data = dataValue;
}
public Node(Object dataValue, Node nextValue, Node previousValue) {
previous = previousValue;
next = nextValue;
data = dataValue;
}
public Object getData() {
return data;
}
public void setData(Object dataValue) {
data = dataValue;
}
public Node getprevious() {
return previous;
}
public void setprevious(Node previousValue) {
previous = previousValue;
}
public Node getNext() {
return next;
}
public void setNext(Node nextValue) {
next = nextValue;
}
}
This adds elements to the list. I think I need to change this part in order to make this into a doubly-linked list, but don't quite understand how?
public MyHistoryList() {
}
// puts element at end of list
public void add(Object data) {
// just getting the node ready
if (head == null) {
head = new Node(data);
}
Node Temp = new Node(data);
Node Current = head;
if (Current != null) {
while (Current.getNext() != null) {
Current = Current.getNext();
}
Current.setNext(Temp);
}
// keeping track of number of elements
incrementCounter();
}
private static int getCounter() {
return counter;
}
private static void incrementCounter() {
counter++;
}
private void decrementCounter() {
counter--;
}
This is just tostring, insertion, deletion, and a few other things. I don't believe anything here needs to be changed to make it a doubly linked list?
public void insert(Object data, int index) {
Node Temp = new Node(data);
Node Current = head;
if (Current != null) {
for (int i = 0; i < index && Current.getNext() != null; i++) {
Current = Current.getNext();
}
}
Temp.setNext(Current.getNext());
Current.setNext(Temp);
incrementCounter();
}
//sees the number of elements
public Object get(int index)
{
if (index < 0)
return null;
Node Current = null;
if (head != null) {
Current = head.getNext();
for (int i = 0; i < index; i++) {
if (Current.getNext() == null)
return null;
Current = Current.getNext();
}
return Current.getData();
}
return Current;
}
// removal
public boolean remove(int index) {
if (index < 1 || index > size())
return false;
Node Current = head;
if (head != null) {
for (int i = 0; i < index; i++) {
if (Current.getNext() == null)
return false;
Current = Current.getNext();
}
Current.setNext(Current.getNext().getNext());
decrementCounter();
return true;
}
return false;
}
public int size() {
return getCounter();
}
public String toString() {
String output = "";
if (head != null) {
Node Current = head.getNext();
while (Current != null) {
output += "[" + Current.getData().toString() + "]";
Current = Current.getNext();
}
}
return output;
}
}
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I am having some issues with my linked list class. I am currently trying to print my favorite bands in the assigned order I gave them, but I am either coming up with the program just prints null or just the band names in the wrong order. I am confused as to why or what I am missing. Any help would be appreciated.
The output I currently get is
Exception in thread "main" java.lang.NullPointerException
at project2.jacobLinkedList.toString(MetalMasher.java:171)
at java.lang.String.valueOf(Unknown Source)
at java.lang.StringBuilder.append(Unknown Source)
at project2.MetalMasher.main(MetalMasher.java:44)
The file is
import java.util.Collections;
import java.util.List;
public class MetalMasher {
public static jacobLinkedList jacobList;
#SuppressWarnings("unchecked")
public static <T> void main(String[] args) {
// this is the default constructor.
jacobList = new jacobLinkedList();
// add elements to the list.
jacobList.add("MegaDeth",1993);
jacobList.add("Slayer",1992);
jacobList.add("Scar Symmetry",2002);
jacobList.add("Gojira",2004);
jacobList.add("Amon Amarth",1997);
System.out.println("Print: jacobList:" + jacobList);
System.out.println(".size():" + jacobList.size());
System.out.println(".remove(2):" + jacobList.remove(2) + " (element removed)");
System.out.println("Print again:" + jacobList);
System.out.println(".remove(1):" + jacobList.remove(1) + " (element removed)");
System.out.println("Print again:" + jacobList);
System.out.println(".remove(1):" + jacobList.remove(1) + " (element removed)");
System.out.println("Print again:" + jacobList);
}
}
class jacobLinkedList {
private static int counter;
private Node head;
// Default constructor
public jacobLinkedList() {
}
// appends the specified element to the end of this list.
public void add(Object data, int i) {
// Initialize Node only incase of 1st element
if (head == null) {
head = new Node(data, i);
}
Node jacobTemp = new Node(data, i);
Node jacobCurrent = head;
if (jacobCurrent != null) {
while (jacobCurrent.getNext() != null) {
jacobCurrent = jacobCurrent.getNext();
}
jacobCurrent.setNext(jacobTemp);
}
// increment the number of elements variable
incrementCounter();
}
private static int getCounter() {
return counter;
}
private static void incrementCounter() {
counter++;
}
private void decrementCounter() {
counter--;
}
// inserts the specified element at the specified position in this list
public void insert(Object data, int i) {
Node jacobTemp = new Node(data, i);
Node jacobCurrent = head;
if (jacobCurrent != null) {
// crawl to the requested index or the last element in the list, whichever comes first
for (int z = 0; z < i && jacobCurrent.getNext() != null; i++) {
jacobCurrent = jacobCurrent.getNext();
}
}
// set the new node's next-node reference to this node's next-node reference
jacobTemp.setNext(jacobCurrent.getNext());
// reference to new node
jacobCurrent.setNext(jacobTemp);
// increment the number of elements variable
incrementCounter();
}
// removes the element at the specified position in this list.
public boolean remove(int index) {
// if the index is out of range, exit
if (index < 1 || index > size())
return false;
Node jacobCurrent = head;
if (head != null) {
for (int i = 0; i < index; i++) {
if (jacobCurrent.getNext() == null)
return false;
jacobCurrent = jacobCurrent.getNext();
}
jacobCurrent.setNext(jacobCurrent.getNext().getNext());
decrementCounter();
return true;
}
return false;
}
// returns the number of elements in this list.
public int size() {
return getCounter();
}
public String toString() {
String output = "";
if (head != null) {
Node jacobCurrent = head.getNext();
while (jacobCurrent != null) {
output += "[" + jacobCurrent.getData().getClass() + "]";
jacobCurrent = jacobCurrent.getNext();
}
}
return output;
}
public class Node {
// reference to the next node in the chain
Node next;
Object data;
// Node constructor
public Node(Object dataValue, Class<Integer> class1) {
next = (Node) null;
data = dataValue;
}
// Node contructor to point towards
#SuppressWarnings("unused")
public Node(Object dataValue, Node ranking) {
next = ranking;
data = dataValue;
}
public Node(Object data, int i) {
// TODO Auto-generated constructor stub
}
public Object getData() {
return data;
}
#SuppressWarnings("unused")
public void setData(Object dataValue) {
data = dataValue;
}
public Node getNext() {
return next;
}
public void setNext(Node nextValue) {
next = nextValue;
}
}
}
From the looks of it, it's most likely the getData method in the Node object that is returning null. That's because you forgot to set the data in the constructor with an object and integer.
public Node(Object data, int i) {
this.data = data;
}
I don't know what the integer is for though.
in toString() method in this line:
output += "[" + jacobCurrent.getData().getClass() + "]";
You need to check when getData() returns null, which it does in most cases for your inputs.
Solution is to check for null before adding string to output. Don't know what you want with it, either add string "null" or skip such cases or fix inputs.
Use:
/**
* Created by MR on 4/27/2016.
*/
import java.util.Collections;
import java.util.List;
public class Test {
public static jacobLinkedList jacobList;
#SuppressWarnings("unchecked")
public static <T> void main(String[] args) {
// this is the default constructor.
jacobList = new jacobLinkedList();
// add elements to the list.
jacobList.add("MegaDeth",1993);
jacobList.add("Slayer",1992);
jacobList.add("Scar Symmetry",2002);
jacobList.add("Gojira",2004);
jacobList.add("Amon Amarth",1997);
System.out.println("Print: jacobList:" + jacobList);
System.out.println(".size():" + jacobList.size());
System.out.println(".remove(2):" + jacobList.remove(2) + " (element removed)");
System.out.println("Print again:" + jacobList);
System.out.println(".remove(1):" + jacobList.remove(1) + " (element removed)");
System.out.println("Print again:" + jacobList);
System.out.println(".remove(1):" + jacobList.remove(1) + " (element removed)");
System.out.println("Print again:" + jacobList);
}
}
class jacobLinkedList {
private static int counter;
private Node head;
// Default constructor
public jacobLinkedList() {
}
// appends the specified element to the end of this list.
public void add(Object data, int i) {
// Initialize Node only incase of 1st element
if (head == null) {
head = new Node(data, i);
}
Node jacobTemp = new Node(data, i);
Node jacobCurrent = head;
if (jacobCurrent != null) {
while (jacobCurrent.getNext() != null) {
jacobCurrent = jacobCurrent.getNext();
}
jacobCurrent.setNext(jacobTemp);
}
// increment the number of elements variable
incrementCounter();
}
private static int getCounter() {
return counter;
}
private static void incrementCounter() {
counter++;
}
private void decrementCounter() {
counter--;
}
// inserts the specified element at the specified position in this list
public void insert(Object data, int i) {
Node jacobTemp = new Node(data, i);
Node jacobCurrent = head;
if (jacobCurrent != null) {
// crawl to the requested index or the last element in the list, whichever comes first
for (int z = 0; z < i && jacobCurrent.getNext() != null; i++) {
jacobCurrent = jacobCurrent.getNext();
}
}
// set the new node's next-node reference to this node's next-node reference
jacobTemp.setNext(jacobCurrent.getNext());
// reference to new node
jacobCurrent.setNext(jacobTemp);
// increment the number of elements variable
incrementCounter();
}
// removes the element at the specified position in this list.
public boolean remove(int index) {
// if the index is out of range, exit
if (index < 1 || index > size())
return false;
Node jacobCurrent = head;
if (head != null) {
for (int i = 0; i < index; i++) {
if (jacobCurrent.getNext() == null)
return false;
jacobCurrent = jacobCurrent.getNext();
}
jacobCurrent.setNext(jacobCurrent.getNext().getNext());
decrementCounter();
return true;
}
return false;
}
// returns the number of elements in this list.
public int size() {
return getCounter();
}
public String toString() {
String output = "";
if (head != null) {
Node jacobCurrent = head.getNext();
while (jacobCurrent.getData() != null) {
output += "[" + jacobCurrent.getData().getClass() + "]";
jacobCurrent = jacobCurrent.getNext();
}
}
return output;
}
public class Node {
// reference to the next node in the chain
Node next;
Object data;
// Node constructor
public Node(Object dataValue, Class<Integer> class1) {
next = (Node) null;
data = dataValue;
}
// Node contructor to point towards
#SuppressWarnings("unused")
public Node(Object dataValue, Node ranking) {
next = ranking;
data = dataValue;
}
public Node(Object data, int i) {
// TODO Auto-generated constructor stub
}
public Object getData() {
return data;
}
#SuppressWarnings("unused")
public void setData(Object dataValue) {
data = dataValue;
}
public Node getNext() {
return next;
}
public void setNext(Node nextValue) {
next = nextValue;
}
}
}
I hope this helps you
I'm trying to create a method to remove nodes from a Binary Tree but I am having a problem, it seems to be ok but I have another method for printing all of them and after "deleting" a specific node I use the print method but it prints all of them including the one I've already deleted.
public class BinaryTree
{
Node root;
Node n;
private class Node
{
public Node f; //father
public Node right;
public Node left;
public int key; // key
public String Student;
public int Mark;
public Node(int key)
{
right = null;
left = null;
f = null;
Student = null;
Mark = 0;
}
}
public void remove()
{
System.out.println("");
System.out.println("Which student do you want to delete? Write down his ID.");
int id = Genio.getInteger();
n = new Node(id);
Node temporal = root;
if(root == null)
{
System.out.println("This tree is empty");
}
else
{
while(temporal != null)
{
n.f = temporal;
if(n.key == temporal.key)
{
if(n.f.right == null && n.f.left == null)
{
n = null;
temporal = null;
}
}
else if(n.key >= temporal.key)
{
temporal = temporal.right;
}
else
{
temporal = temporal.left;
}
}
}
}
}
I am learning Java SE and am currently at simple linked lists (page 687/1047 of Savitch's Absolute Java).
I am stuck at instantiating the LinkList in the main method of my demo class:
LinkedList1 list = new LinkedList1();
I tried using breakpoint and it indicates a ReflectiveOperationException.
This is the code:
public class Node1
{
private String item;
private int count;
private Node1 link;
public Node1()
{
link = null;
item = null;
count = 0;
}
public Node1(String newItem, int newCount, Node1 linkValue)
{
setData(newItem, newCount);
link = linkValue;
}
public void setData(String newItem, int newCount)
{
item = newItem;
count = newCount;
}
public void setLink(Node1 newLink)
{
link = newLink;
}
public String getItem()
{
return item;
}
public int getCount()
{
return count;
}
public Node1 getLink()
{
return link;
}
}
This is the LinkedList1 class:
public class LinkedList1
{
private Node1 head;
public LinkedList1()
{
head = null;
}
/**
* Adds a node at the start of the list with the specified data.
* The added node will be the first node in the list.
*/
public void add(String itemName, int itemCount)
{
head = new Node1(itemName, itemCount, head);
}
/**
* Removes the head node and returns true if the list contains at least
* one node. Returns false if the list is empty.
*/
public boolean deleteHeadNode()
{
if (head != null)
{
head = head.getLink();
return true;
}
else
return false;
}
/**
* Returns the number of nodes in the list.
*/
public int size()
{
int count = 0;
Node1 position = head;
while (position != null)
{
count++;
head = position.getLink();
}
return count;
}
public boolean contains(String item)
{
return (find(item) != null);
}
/**
* Finds the first node containing the target item, and returns a
* reference to that node. If the target is not in the list, null is returned.
*/
public Node1 find(String target)
{
Node1 position = head;
String itemAtPosition;
while(position != null)
{
itemAtPosition = position.getItem();
if(itemAtPosition.equals(target))
{
return position;
}
position = position.getLink();
}
return null; //target was not found
}
public void outputList()
{
Node1 position = head;
while (position != null)
{
System.out.println(position.getItem() + " " + position.getCount());
position = position.getLink();
}
}
}
I think that the problem has something to do with the constructor of Node1 having the member link of type Node1. I'm trying to understand how these data structures work and not just resort to using the built-in ArrayList(& APIs) for my projects. Can you guys have a look and point me in the right direction. Any help would be very much appreciated.
This is my main method.
public class LinkedListDemo
{
public static void main(String[] args)
{
try
{
LinkedList1 list = new LinkedList1();
list.add("apples", 1);
list.add("bananas", 2);
list.add("cantaloupe", 3);
System.out.println("List has "+ list.size() + " nodes.");
list.outputList();
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
}
}
Your size method contains an infinite loop which explain why the outputs are never reached.
while (position != null)
{
count++;
head = position.getLink();
}
You are looping until position is null, but never assign anything to position and instead assign to head. Instead, you want to do
while (position != null)
{
count++;
position = position.getLink();
}
Now you would get the output
List has 3 nodes.
cantaloupe 3
bananas 2
apples 1