Inserting right children on left side of BST, and vice versa - java

I'm having a little bit of difficulty with my insert method for this homework assignment. I have most of it done, but for some reason whenever my program is supposed to insert a node as a right child on the left side of the tree it just inserts it as a left child.
I kind of do my comparison in a weird way (signs should be reversed for a lot of them, but it worked like that for some reason) so please bear with me if you have difficulty in reading it.
I know that this is a horrible way to implement a binary search tree, and I would never ever do it in the real world, but it's homework and thus -- I have no choice.
Any and all help is appreciated, as always. Thank you!
Edit: I know where the problem is now. It's within the searchFor() method. Instead of the node's rightful parent, it makes the parent the root of the tree (in this case the parent of the node is always "cup".)
now that that's out of the way, can anyone offer up a solution?
Edit2: Took some of the extra stuff out that I don't think is relevant to the problem. I'm pretty sure I've narrowed it down to the searchFor() method. Whenever I call to return the parent of the current node, it will return the root of the tree ("cup.") I think that's why I'm having my problems, since it inserts based on that.
Thanks for all the help so far, I really appreciate it.
public class BinarySearchTree //implements Comparator
{
private Comparator<Object> dataComparator;
private LinkedListWithTwoLinks tree;
public static void main (String[] args)
{
BinarySearchTree bst;
Object hold;
String[] words = {"cup", "shaker", "cord", "key", "addressbook", "date", "address", "cupcake",
"card", "tape", "page", "day", "key", "days", "dayt"};
bst = new BinarySearchTree(new AlphabeticComparator());
System.out.println("[1]: original tree");
for(int i=0; i<words.length; i++) if (!bst.insert(words[i])) { System.out.println(">>>>>>>>>>>>> " + words[i] + " is already in tree"); }
bst.inOrder();
}
public static class AlphabeticComparator implements Comparator <Object>
{
public int compare(Object x, Object y)
{
if ( x == y ) return 0;
if ( x == null) return -1;
if ( y == null) return 1;
return (x.toString().compareTo(y.toString()));
}
}
public static class LastCharacterComparator implements Comparator <Object>
{
public int compare(Object x, Object y)
{
String xs;
String ys;
if ( x == y ) return 0;
if ( x == null ) return -1;
if ( y == null) return 1;
xs = x.toString();
ys = y.toString();
if ( xs.length() == 0) return -1;
if ( ys.length() == 0) return 1;
return (xs.charAt(xs.length()-1) - ys.charAt(ys.length()-1));
}
}
public BinarySearchTree(Comparator<Object> y)
{
dataComparator = y;
this.tree = new LinkedListWithTwoLinks();
}
private int compare(BinarySearchTreeElementInterface s, Object data)
{
return this.dataComparator.compare(s, data);
}
public boolean insert(Object data)
{
boolean success;
BinarySearchTreeElementInterface current;
BinarySearchTreeElementInterface parent;
current = getRoot();
parent = null;
success = false;
if (current == null)
{
getTree().insert(data);
return true;
}
else
{
SearchResult insert;
insert = searchFor(data);
//if (data == "shaker") {System.out.println(insert.resultOfCompare); }
while (current != null)
{
if (insert.insertAsLeftChild())
{
//if (data == "card") {System.out.println("IN RIGHT");}
//System.out.println("IN LEFT");
parent = current;
current = current.getLeftChild();
}
else if (insert.insertAsRightChild())
{
//if (data == "card") {System.out.println("IN RIGHT");}
parent = current;
current = current.getRightChild();
}
}
if (insert.insertAsLeftChild())
{
//parent.setLeftChild(insert.getParentOfLocation()); //insert.getParentOfLocation()
//System.out.println(data);
getTree().insertUsingPrior(parent, data);
//System.out.println(insert.getParentOfLocation()+" bye left");
// System.out.println(insert.getLocation()+" hi");
success = true;
}
else if (insert.insertAsRightChild())
{
//parent.setRightChild(insert.getParentOfLocation());
//System.out.println(data);
getTree().insertUsingNext(parent, data);
//System.out.println(insert.getParentOfLocation()+" bye right");
// System.out.println(insert.getLocation());
success = true;
}
else {success = false;}
/*
figures out if it should be inserted as a left or right child
then call insert using prior/next
}*/
}
return success;
}
private SearchResult searchFor(Object data)
{
/*returns either to node containing the data or the parent of the node of which the data would be a child of*/
if (getTree() == null) {throw new ListEmptyException("Tree is empty!");}
BinarySearchTreeElementInterface currentLocation;
BinarySearchTreeElementInterface parent;
SearchResult destination;
parent = getRoot();
currentLocation = parent;
while (currentLocation != null)
{
if (currentLocation.getData() == data)
{
return new SearchResult(parent, currentLocation, compare(currentLocation, data));
}
if (compare(currentLocation, data) < 0)
{
//System.out.println("IN LEFT");
parent = currentLocation;
currentLocation = currentLocation.getLeftChild();
}
else if (compare(currentLocation, data) > 0)
{
//System.out.println("IN RIGHT");
parent = currentLocation;
currentLocation = currentLocation.getRightChild();
}
}
destination = new SearchResult(parent, currentLocation, compare(parent, data));
//System.out.println(destination.resultOfCompare);
return destination;
/*
* use nothing but BSTEIs
*/
}
public void inOrder()
{
inOrder(getRoot());
}
public void inOrder(BinarySearchTreeElementInterface BSTroot)
{
//System.out.println(BSTroot.getRightChild());
if (BSTroot != null)
{
inOrder(BSTroot.getLeftChild());
System.out.println(BSTroot.getData());
inOrder(BSTroot.getRightChild());
}
/*if (BSTroot.getLeftChild() != null)
{
}
System.out.println(BSTroot.getData());
if (BSTroot.getRightChild() != null)
{
inOrder(BSTroot.getRightChild());
//System.out.println(BSTroot.getData());
}
System.out.println(BSTroot.getData());*/
}
public int size()
{
return tree.size();
}
/*SEARCH RESULT CLASS-----------------------------------------------------------------------------------------*/
public class SearchResult
{
BinarySearchTreeElementInterface location;
BinarySearchTreeElementInterface parentOfLocation;
int resultOfCompare;
public SearchResult(BinarySearchTreeElementInterface parent, BinarySearchTreeElementInterface locate, int comp)
{
this.parentOfLocation = parent;
this.location = locate;
this.resultOfCompare = comp;
}
public BinarySearchTreeElementInterface getLocation()
{
return this.location;
}
public BinarySearchTreeElementInterface getParentOfLocation()
{
return this.parentOfLocation;
}
public boolean insertAsLeftChild()
{
if (resultOfCompare > 0) {return true;}
else {return false;}
}
public boolean insertAsRightChild()
{
if (resultOfCompare < 0) {return true;}
else {return false;}
}
public boolean locationIsLeftOfParent()
{
return this.location == parentOfLocation.getLeftChild();
}
public boolean locationisRightOfParent()
{
return this.location == parentOfLocation.getRightChild();
}
public boolean wasSearchSuccessful()
{
return this.parentOfLocation == this.location;
}
public void setLocation(BinarySearchTreeElementInterface newLocation)
{
this.location = newLocation;
}
public void setLocationOfParent(BinarySearchTreeElementInterface newParentLocation)
{
this.parentOfLocation = newParentLocation;
}
}
}

compare(x, y) method of BinarySearchTree is wrong.
It compares a node to a data with a comparator made to compare data against data. Change 'Object' to 'String' and it will not compile while your sample data are strings.
This should fix it:
private int compare(BinarySearchTreeElementInterface s, Object data)
{
return this.dataComparator.compare(s.getData(), data);
}

In your SearchResult class, do you have the way it determines a left or right insert swapped?
public boolean insertAsLeftChild()
{
if (resultOfCompare > 0) {return true;}
else {return false;}
}
If the compare is greater than 0, it should be interested as a right child, correct?

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 properly use a generic implementation of a binary search tree [duplicate]

This question already has answers here:
How to implement the Java comparable interface?
(9 answers)
Closed 4 years ago.
I wrote a binary search tree & binary search node classes and I'm not so good with generics so I tried to do it with generics .
Now whenever I create a binary tree of the class I wrote it's perfectly okay to set the parameter type to String for instance, but if I create my own type then It doesn't let me use it. I'll explain , here's my BinaryNode & BinaryTree class, as well as the type Name I created myself which is essentially a string but I just wanted to test it:
BinaryNode:
public class BinaryNode<T extends Comparable<T>> {
T data;
BinaryNode<T> left;
BinaryNode<T> right;
public BinaryNode (T data){
this.data = data;
}
public BinaryNode (){
this(null);
}
//insert
public void insert(T data){
// if data is less than node's data , then if left is null insert , if not do the same for left
if(this.data.compareTo(data) > 0){
if(this.left == null){
left = new BinaryNode<>(data);
}
else {
left.insert(data);
}
}
// if data is greater than node's data , then if right is null insert , if not do the same for right
else if(this.data.compareTo(data) < 0) {
if (this.right == null) {
right = new BinaryNode<>(data);;
}
else{
right.insert(data);
}
}
// if it's equal to node's data do nothing as we do not allow duplicate values.
}
public void traverseInOrder(){
if(this.left != null){
left.traverseInOrder();
}
System.out.println(this.data);
if(this.right != null){
right.traverseInOrder();
}
}
public BinaryNode getMin(){
if(left !=null) {
return left.getMin();
}
return this;
}
public BinaryNode getMax(){
if(right !=null){
return right.getMax();
}
return this;
}
public BinaryNode get(T data){
if(this.data.compareTo(data) > 0){
if(this.left == null) {
return null;
}
return left.get(data);
}
if(this.data.compareTo(data) < 0){
if(this.right == null){
return null;
}
return right.get(data);
}
return this;
}
#Override
public String toString() {
return "data = " + data ;
}
}
BinaryTree:
public class BinaryTree<T extends Comparable<T>> {
BinaryNode<T> root;
public BinaryTree(T data){
root = new BinaryNode<T>(data);
}
public BinaryTree(){
root = null;
}
public void insert(T data){
if(root == null){
root = new BinaryNode<T>(data);
}
else{
root.insert(data);
}
}
public void traverseInOrder(){
if(root == null){
return;
}
root.traverseInOrder();
}
public BinaryNode getMin(){
if(root == null){
return null;
}
return root.getMin();
}
public BinaryNode getMax(){
if(root == null){
return null;
}
return root.getMax();
}
public BinaryNode get(T data){
if(root == null){
return null;
}
return root.get(data);
}
}
Name:
public class Name implements Comparable {
String name;
public Name(String name){
this.name = name;
}
public Name(){
this("");
}
#Override
public int compareTo(Object o) {
if(!(o instanceof Name)) throw new IllegalArgumentException();
String n1 = this.name.toLowerCase();
String n2 = ((Name) o).name.toLowerCase();
for(int i = 0; i< n1.length() && i< n2.length() ; i++ ){
if(n1.charAt(i) > n2.charAt(i)) return 1;
if(n2.charAt(i) > n1.charAt(i)) return -1;
}
if(n1.length() > n2.length()) return -1;
if(n2.length() > n1.length()) return 1;
return 0;
}
public String toString(){
return name;
}
}
Now I can easily create a binary tree in Main like so:
BinaryTree<String> nametree = new BinaryTree<>();
But if I wanted to do something like:
BinaryTree<Name> nametree = new BinaryTree<>();
then I get a compilation error unless I go and change Comparable to Comparable in the BinaryNode and BinaryTree classes,
and I feel I don't have a good grasp of generics so if anyone could please clarify what is wrong with doing what I did. and anything else that could help me make a better and correct use of generics that'd be great.
Thanks in advance !
The problem might be that the Comparable interface requires a type when you are implementing it in Name.
Try setting the class definition of Name to be: public class Name implements Comparable<Name>
This answer gives a good explanation: Java- The meaning of <T extends Comparable<T>>?

Binary search tree Searching troubleshooting

I've spent about two days pouring over this and I have no idea what's missing. Originally my BST used comparables, then I switched it to int to simplify it when it wasn't working.
I add several items to a tree and it successfully prints them out in order. Then, the first time I call the search() method it returns true, as it should. Every other search call after that returns false whether it is true or false.
I'm including most of my code here in case the problem isn't related with the search method itself.
The output SHOULD be: 4 12 23 27 30 42 60 84 true true false true true
but instead I get: 4 12 23 27 30 42 60 84 true false false false false
public class BSTree {
TreeNode root;
static int comparison;
public void insert(int value) {
if (root == null) {
root = new TreeNode(value);
}
else {
root.insert(value);
}
}
public boolean search(int chicken) {
if (root != null ) {
return root.search(chicken);
}
return false;
}
public static int height(TreeNode b) {
return TreeNode.height(b);
}
public static void CompareSet() {
comparison++;
}
public int getCompare() {
return comparison;
}
public void ResetCompare() {
comparison = 0;
}
public static void traverseInOrder (TreeNode node) {
if (node != null) {
traverseInOrder(node.left);
System.out.print(" " + node.data);
traverseInOrder (node.right);
}
}
public static void main(String args[]) {
BSTree tree = new BSTree();
tree.insert(30);
tree.insert(42);
tree.insert(84);
tree.insert(12);
tree.insert(4);
tree.insert(23);
tree.insert(27);
tree.insert(60);
traverseInOrder(tree.root);
System.out.println("\n" + tree.search(30));
System.out.println("\n" + tree.search(4));
System.out.println("" + tree.search(50));
System.out.println("" + tree.search(27));
System.out.println("" + tree.search(42));
System.out.println(height(tree.root));
}
}
Here is the treeNode class:
public class TreeNode<T> {
int data;
TreeNode left;
TreeNode right;
TreeNode(int value){
this.data = value;
//right = null;
//left = null;
}
public void insert(int value) {
if (value == data) {
return;
}
if (value < data) {
if (left == null) {
left = new TreeNode(value);
}
else {
left.insert(value);
}
}
else {
if (right == null) {
right = new TreeNode(value);
}
else {
right.insert(value);
}
}
public boolean search(int value) {
BSTree.CompareSet();
if (data == value) return true;
if (data < value && left!=null)
return left.search(value);
else if(data > value && right != null)
return right.search(value);
return false;
}
public static int height(TreeNode b) {
if (b == null) return -1;
return 1 + Math.max(height(b.left), height(b.right));
}
public int getData(){
return data;
}
public TreeNode getLeftChild() {
return left;
}
public void setLeftChild(TreeNode leftChild) {
this.left = leftChild;
}
public TreeNode getRightChild() {
return right;
}
public void setRightChild(TreeNode rightChild) {
this.right = rightChild;
}
}
Your comparaisons are reversed :))) Here is the corrected TreeNode::search method :
public boolean search(int value) {
BSTree.CompareSet();
if (data == value) return true;
if (data > value && left!=null)
return left.search(value);
else if(data < value && right != null)
return right.search(value);
return false;
}
I think you swapped the data and the value variables.
just change your search method of TreeNode class to this:
public boolean search(int value) {
Test.CompareSet();
if (data == value) return true;
if (data < value && right!=null)
return right.search(value);
else if(data > value && left != null)
return left.search(value);
return false;
}
When your current node's data is greater than value you need to go to left sub-tree. And when current node's data is smaller than value you need to go to right sub-tree. You just have done the reverse one.

Java linked list how to make a private method to handle searching

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

Remove method in a binary tree

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

Categories

Resources