Remove method in a binary tree - java

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;
}
}
}
}
}

Related

Eclipse suspends my process in debug mode

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.

How do I reference a method to add to a binaryTree?

I am tasked with building a BinaryTree that represents Morse Code. It branches left with each dot and right with each dash.
I can not figure out, however, why my method to add a Node does not seem to want to work with a BinaryTree object. IntelliJ says that it "can not resolve method".
I am certain that the BinaryTree is not the issue, because I was given detailed instructions on how to write the class by my instructor. Rather, I suspect that I am perhaps referencing the wrong thing here. I have already verified that the parameters being entered isn't the issue.
public static MorseCodeTree<Character> readMorseCodeTree()
{
MorseCodeTree<Character> morse = new MorseCodeTree<Character>();
Node<Character> newNode = new Node<Character>(null);
morse.addNode(newNode, letter, position);
private Node<Character> addNode(Node<Character> currentNode, char data, String morseCode)
{
if (currentNode == null)
{
currentNode = new Node(null);
}
if (morseCode.charAt(0) == '*')
{
currentNode = addNode(currentNode.left, data, morseCode.substring(1));
}
else if (morseCode.charAt(0) == '-')
{
currentNode = addNode(currentNode.right, data, morseCode.substring(1));
}
else
{
currentNode.data = data;
}
return currentNode;
}
BinaryTree class:
import java.io.Serializable;
import java.util.Scanner;
public class BinaryTree implements Serializable{
//implement Node class
protected static class Node<E> implements Serializable
{
protected E data;
protected Node<E> left;
protected Node<E> right;
public Node (E data)
{
this.data = data;
this.left = null;
this.right = null;
}
public String toString()
{
return data.toString();
}
}
protected Node root;
public BinaryTree()
{
root = null;
}
protected BinaryTree(Node<E> root)
{
this.root = root;
}
public BinaryTree(E data, BinaryTree<E> leftTree, BinaryTree<E> rightTree)
{
root = new Node<E>(data);
if (leftTree != null)
{
root.left = leftTree.root;
}
else
{
root.left = null;
}
if (rightTree != null)
{
root.right = rightTree.root;
}
else
{
root.right = null;
}
}
public BinaryTree<E> getLeftSubtree()
{
if (root != null && root.left != null)
{
return new BinaryTree<E>(root.left);
}
else
{
return null;
}
}
public BinaryTree<E> getRightSubtree()
{
if (root != null && root.right != null)
{
return new BinaryTree<E>(root.right);
}
else
{
return null;
}
}
public boolean isLeaf()
{
return (root.left == null && root.right == null);
}
public String toString()
{
StringBuilder sb = new StringBuilder();
preOrderTraverse(root, 1, sb);
return sb.toString();
}
private void preOrderTraverse(Node<E> node, int depth, StringBuilder sb)
{
for (int i = 1; i < depth; i++)
{
sb.append(" ");
}
if (node == null)
{
sb.append("null\n");
}
else
{
sb.append(node.toString() + "\n");
preOrderTraverse(node.left, depth + 1, sb);
preOrderTraverse(node.right, depth + 1, sb);
}
}
public static BinaryTree<String> readBinaryTree(Scanner scan)
{
String data = scan.next();
if (data.equals("null"))
{
return null;
}
else
{
BinaryTree<String> leftTree = readBinaryTree(scan);
BinaryTree<String> rightTree = readBinaryTree(scan);
return new BinaryTree<String>(data, leftTree, rightTree);
}
}
}
You're declaring the addNode(...) method within readMorseCodeTree(), so it's not in the scope of the class. The latter method should look like this:
public static BinaryTree<Character> readMorseCodeTree()
{
BinaryTree morse = new MorseCodeTree();
Node<Character> newNode = new Node<Character>(null);
morse.addNode(newNode, letter, position);
}

Creating a binary search tree in java. But output is null

I am trying to create a rudimentary binary search tree in java with an insert and traverse method. The nodes have two local variables, a string and an int, the String value is used to sort the nodes.
Each BST has a local variable pointer to the root node and the nodes are inserted by traversing from the node. There seems to be a problem in creating the root node as my output is consistently producing null instead of.
THE
CAT
HAT
class BST
{
public Node root = null;
private class Node
{
private String key;
private int value;
private Node left;
private Node right;
public Node ()
{
}
public Node (String key, int value)
{
this.key = key;
this.value = value;
}
public String toString ()
{
return ("The key is: "+ this.key +" "+ this.value);
}
}
BST ()
{
}
public void put (String key, int value)
{
put (root, key, value);
}
private void put (Node x, String key, int value)
{
Node newNode = new Node(key, value);
if (x == null)
{
x = newNode;
System.out.println("new node added");
System.out.println(x);
}
int cmp = key.compareTo(x.key);
if (cmp < 0)
put(x.left, key, value);
else if (cmp > 0)
put(x.right, key, value);
else
x.value = value;
}
public void inorder (Node x)
{
if (x != null)
{
inorder (x.left);
System.out.println(x.key);
inorder (x.right);
}
}
public static void main (String [] args)
{
BST bst = new BST();
bst.put(bst.root,"THE", 1);
bst.put(bst.root,"CAT", 2);
bst.put("HAT", 1);
bst.inorder(bst.root);
}
}
Parameters are passed by value. Use the method's return value to alter something:
public void put (String key, int value)
{
root = put (root, key, value);
}
private Node put (Node x, String key, int value)
{
Node newNode = new Node(key, value);
if (x == null)
{
System.out.println("new node added");
System.out.println(x);
return newNode;
}
int cmp = key.compareTo(x.key);
if (cmp < 0)
x.left = put(x.left, key, value);
else if (cmp > 0)
x.right = put(x.right, key, value);
else
x.value = value;
return x;
}
Refer below link , good explanation of BST
http://www.java2novice.com/java-interview-programs/implement-binary-search-tree-bst/
A binary search tree is a node-based data structure, the whole idea of a binary search tree is to keep the data in sorted order so we can search the data in a little faster.There are three kinds of nodes are playing key role in this tree (Parent Node,Left Child Node & Right Child Node).The value of the left child node is always lesser than the value of the parent node, the same as the value of the right child node is always greater than the value of the parent node. Each parent node can have a link to one or two child nodes but not more than two child nodes.
Please find the source code from my tech blog - http://www.algonuts.info/create-a-binary-search-tree-in-java.html
package info.algonuts;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
class BinaryTreeNode {
int nodeValue;
BinaryTreeNode leftChildNode;
BinaryTreeNode rightChildNode;
public BinaryTreeNode(int nodeValue) {
this.nodeValue = nodeValue;
this.leftChildNode = null;
this.rightChildNode = null;
}
public void preorder() {
System.out.print(this.nodeValue+" ");
if(this.leftChildNode != null) {
this.leftChildNode.preorder();
}
if(this.rightChildNode != null) {
this.rightChildNode.preorder();
}
}
public void inorder() {
if(this.leftChildNode != null) {
this.leftChildNode.inorder();
}
System.out.print(this.nodeValue+" ");
if(this.rightChildNode != null) {
this.rightChildNode.inorder();
}
}
public void postorder() {
if(this.leftChildNode != null) {
this.leftChildNode.postorder();
}
if(this.rightChildNode != null) {
this.rightChildNode.postorder();
}
System.out.print(this.nodeValue+" ");
}
}
class BinaryTreeCompute {
private static BinaryTreeNode temp;
private static BinaryTreeNode newNode;
private static BinaryTreeNode headNode;
public static void setNodeValue(int nodeValue) {
newNode = new BinaryTreeNode(nodeValue);
temp = headNode;
if(temp != null)
{ mapping(); }
else
{ headNode = newNode; }
}
private static void mapping() {
if(newNode.nodeValue < temp.nodeValue) { //Check value of new Node is smaller than Parent Node
if(temp.leftChildNode == null)
{ temp.leftChildNode = newNode; } //Assign new Node to leftChildNode of Parent Node
else
{
temp = temp.leftChildNode; //Parent Node is already having leftChildNode,so temp object reference variable is now pointing leftChildNode as Parent Node
mapping();
}
}
else
{
if(temp.rightChildNode == null)
{ temp.rightChildNode = newNode; } //Assign new Node to rightChildNode of Parent Node
else
{
temp = temp.rightChildNode; //Parent Node is already having rightChildNode,so temp object reference variable is now pointing rightChildNode as Parent Node
mapping();
}
}
}
public static void preorder() {
if(headNode != null) {
System.out.println("Preorder Traversal:");
headNode.preorder();
System.out.println("\n");
}
}
public static void inorder() {
if(headNode != null) {
System.out.println("Inorder Traversal:");
headNode.inorder();
System.out.println("\n");
}
}
public static void postorder() {
if(headNode != null) {
System.out.println("Postorder Traversal:");
headNode.postorder();
System.out.println("\n");
}
}
}
public class BinaryTree {
//Entry Point
public static void main(String[] args) {
ArrayList <Integer> intList = new ArrayList <Integer>(Arrays.asList(50,2,5,78,90,20,4,6,98));
Iterator<Integer> ptr = intList.iterator();
while(ptr.hasNext())
{ BinaryTreeCompute.setNodeValue(ptr.next()); }
BinaryTreeCompute.preorder();
BinaryTreeCompute.inorder();
BinaryTreeCompute.postorder();
}
}
Adding to the answer by #Maurice,
Your code has several problems:
You expect JAVA to be pass by reference, when it is pass by value. You should use the code given by Maurice instead.
You are comparing "keys", when you should compare values.
I suggest that you use following modified code :
public class BST
{
public Node root = null;
private class Node
{
private String key;
private int value;
private Node left;
private Node right;
public Node ()
{
}
public Node (String key, int value)
{
this.key = key;
this.value = value;
}
public String toString ()
{
return ("The key is: "+ this.key +" "+ this.value);
}
}
BST ()
{
}
public void put (String key, int value)
{
root = putInTree (root, key, value);
}
private Node putInTree (Node x, String key, int value)
{
Node newNode = new Node(key, value);
if (x == null)
{
x = newNode;
System.out.println("new node added");
System.out.println(x);
return newNode;
}
//int cmp = key.compareTo(x.key);
if (value < x.value)
x.left = putInTree(x.left, key, value);
else /*if (value >= x.value)*/
x.right = putInTree(x.right, key, value);
/*else
x.value = value;*/
return x;
}
public void inorder (Node x)
{
if (x != null)
{
inorder (x.left);
System.out.println(x.key);
inorder (x.right);
}
}
public static void main (String[] args)
{
BST bst = new BST();
bst.put("THE", 1);
bst.put("CAT", 2);
bst.put("HAT", 1);
bst.inorder(bst.root);
}
}

Java: Converting a single-linked list into a doubly linked list from scratch

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;
}
}

Java linked list node print Error [duplicate]

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

Categories

Resources