I am new on JAVA and if can't understand what is wrong in my Insert method.
The head node never update and nothing is going on display.
public class BinarySearchTree {
private Node head;
/**
* This is a default constructor for the root of the binary search tree
*/
public BinarySearchTree() {
head = null;
}
public Node Insert(Node head, Node node) {
if (head == null)
head = node;
else if (node.data < head.data)
head.left = Insert(head.left, node);
else if (node.data > head.data)
head.right = Insert(head.right, node);
return head;
If I use on the constructor head = new Node(), I get the tree but node with data=0 is add to my tree.
How can I prevent that?
Thank you
EDIT:
public class Node {
int data;
Node right;
Node left;
Node parent;
/**
* Constructor for the root in binary search tree
*/
public Node() {
}
public Node(int data) {
this.data = data;
this.right = null;
this.left = null;
//this.parent = null;
}
public Node(Node obj){
if(obj != null){
this.data = obj.data;
this.left = obj.left;
this.right = obj.right;
}
}
public void setData(int data, Node right, Node left, Node parent) {
this.data = data;
this.right = right;
this.left = left;
//this.parent = parent;
}
public int getData() {
return data;
}
public class BinarySearchTree {
private Node head;
/**
* This is a default constructor for the root of the binary search tree
*/
public BinarySearchTree() {
head = new Node();
}
public Node Insert(Node head, Node node) {
if (head == null)
head = node;
else if (node.data < head.data)
head.left = Insert(head.left, node);
else if (node.data > head.data)
head.right = Insert(head.right, node);
return head;
}
////////////////////////////////////////////////////////////////////////////////
public void printInOrder(Node node)
{
if (node != null)
{
printInOrder(node.left);
System.out.print(node.data + " - ");
printInOrder(node.right);
}
}
public void printPostOrder(Node node)
{
if (node != null)
{
printPostOrder(node.left);
printPostOrder(node.right);
System.out.print(node.data + " - ");
}
}
public void printPreOrder(Node node)
{
if (node != null)
{
System.out.print(node.data + " - ");
printPreOrder(node.left);
printPreOrder(node.right);
}
}
public Node getHead(){
return head;
}
////////////////////////////////////////////////////////////////////////////////
public static void main(String[] args)
{
BinarySearchTree f = new BinarySearchTree();
/**
* Insert
*/
f.Insert(f.head, new Node(20));
f.Insert(f.head, new Node(5));
f.Insert(f.head, new Node(25));
f.Insert(f.head, new Node(3));
f.Insert(f.head, new Node(7));
f.Insert(f.head, new Node(27));
f.Insert(f.head, new Node(27));
/**
* Print
*/
f.printInOrder(f.head);
System.out.println("");
f.printPostOrder(f.head);
System.out.println("");
f.printPreOrder(f.head);
System.out.println("");
}
The problem is that your function Insert has an input named head
This means in the funtion head is not the head of your class, but the passed value. And the java does it's pass-by-value and well...
Try this instead of your Insert:
private Node recursiveInsert(Node head, Node node) {
if (head == null)
head = node;
else if (node.data < head.data)
head.left = recursiveInsert(head.left, node);
else if (node.data > head.data)
head.right = recursiveInsert(head.right, node);
return head;
}
public Node insert(Node node){
if(this.head==null){
this.head=node;
}else{
recursiveInsert(this.head,node);
}
return this.head;
}
And change the calls
f.Insert(f.head, new Node(20));
f.Insert(f.head, new Node(5));
f.Insert(f.head, new Node(25));
f.Insert(f.head, new Node(3));
f.Insert(f.head, new Node(7));
f.Insert(f.head, new Node(27));
f.Insert(f.head, new Node(27));
to
f.insert(new Node(20));
f.insert(new Node(5));
f.insert(new Node(25));
f.insert(new Node(3));
Tell me if it works ;)
Related
i'm studying a Binary Search Tree.
I use method inOrder kind of traversals but in main method i get an error. The question is why? What do i miss?
Thank you
inOrder(S11.Tree<java.lang.Integer>.Node<java.lang.Integer>)
in Tree cannot be applied to(S11.Node<java.lang.Integer>)
public class Tree<T extends Comparable<T>> {
private Node<T> root;
public void add(T data) {
root = doInsert(root, data);
}
public Node<T> doInsert(Node<T> root, T data) {
if (root == null) {
return new Node<T>(data);
} else if (data.compareTo(root.data) > 0) {
root.right = doInsert(root.right, data);
} else if (data.compareTo(root.data) < 0) {
root.left = doInsert(root.left, data);
}
return root;
}
public void inOrder(Node<T> root) {
if (root != null) {
inOrder(root.left);
System.out.print(root.data + " ");
inOrder(root.right);
}
}
class Node<T> {
Node<T> left;
Node<T> right;
T data;
public Node(T data) {
this.data = data;
}
}
}
public static void main(String[] args) {
Tree<Integer> tree = new Tree<Integer>();
Node<Integer> root1 = new Node<>(8);
tree.add(3);
tree.add(10);
tree.add(1);
tree.add(6);
tree.add(14);
tree.add(4);
tree.add(7);
tree.add(13);
tree.add(18);
tree.inOrder(**root1)**;//here I get an error
}
}
You have a design problem here as well as incorrect implementation of add(T data) method.
public final class Tree<T extends Comparable<T>> {
private Node<T> root;
private int size;
public void add(T val) {
Node<T> node = new Node<>(val);
if (root == null)
root = node;
else
add(root, node);
size++;
}
private void add(Node<T> parent, Node<T> node) {
if (node.val.compareTo(parent.val) < 0) {
if (parent.left == null)
parent.left = node;
else
add(parent.left, node);
} else if (parent.right == null)
parent.right = node;
else
add(parent.right, node);
}
public List<T> inOrder() {
return size == 0 ? Collections.emptyList() : Collections.unmodifiableList(inOrder(root, new ArrayList<>(size)));
}
private static <T> List<T> inOrder(Node<T> node, List<T> res) {
while (true) {
if (node == null)
return res;
inOrder(node.left, res);
res.add(node.val);
node = node.right;
}
}
// This is an internal implementation of Tree and should be hidden
// Node should not be linked with Tree instance
private static final class Node<T> {
private final T val;
private Node<T> left;
private Node<T> right;
public Node(T val) {
this.val = val;
}
}
}
Output:
Tree<Integer> tree = new Tree<>();
tree.add(8);
tree.add(3);
tree.add(10);
tree.add(1);
tree.add(6);
tree.add(14);
tree.add(4);
tree.add(7);
tree.add(13);
tree.add(18);
System.out.println(tree.inOrder()); // [1, 3, 4, 6, 7, 8, 10, 13, 14, 18]
I am having a little trouble iterating a linked list for an assignment.
Linked list class / Node class
(no size methods & cannot modify/add methods)
class MyGenericLinkedList<S> {
Node<S> front;
public MyGenericLinkedList() {
front = null;
}
public void add(S value) {
if (front == null) {
front = new Node<S>(value);
} else {
Node<S> current = front;
while (current.next != null) {
current = current.next;
}
current.next = new Node<S>(value);
}
}
public S get(int index) {
Node<S> current = front;
for (int i = 0; i < index; i++) {
current = current.next;
}
return (S)current.data;
}
public void remove(int index) {
if (index == 0) {
front = front.next;
} else {
Node<S> current = front;
for (int i = 0; i < index - 1; i++) {
current = current.next;
}
current.next = current.next.next;
}
}
}
/*** DO NOT MAKE ANY CHANGE TO CLASS Node ***/
class Node<X> {
X data;
Node<X> next;
public Node(X data) {
this.data = data;
this.next = null;
}
public Node(X data, Node<X> next) {
this.data = data;
this.next = next;
}
}
Here is what I am trying to use to iterate the list but is not running
while(node.children.front != null) {
System.out.println(node.children.front);
node.children.remove(0);
}
My full java file:
/*** DO NOT ADD A NEW IMPORT DECLARATION HERE ***/
/*** DO NOT MAKE ANY CHANGE TO CLASS A5 EXCEPT THE PLACEHOLDER TO FILL IN ***/
/*** YOU CANNOT ADD A NEW FIELD VARIABLE ***/
/*** YOU CANNOT ADD A NEW METHOD DECLARATION ***/
public class A5 {
public static void main(String[] args) {
//---------------------------------------------------------------------
TreeNode root = new TreeNode(1);
MyGenericLinkedList<TreeNode> children = new MyGenericLinkedList();
TreeNode two = new TreeNode(2);
TreeNode three = new TreeNode(3);
TreeNode four = new TreeNode(4);
TreeNode five = new TreeNode(5);
TreeNode six = new TreeNode(6);
TreeNode seven = new TreeNode(7);
TreeNode eight = new TreeNode(8);
TreeNode nine = new TreeNode(9);
TreeNode ten = new TreeNode(10);
TreeNode eleven = new TreeNode(11);
TreeNode twelve = new TreeNode(12);
TreeNode thirteen = new TreeNode(13);
TreeNode fourteen = new TreeNode(14);
children.add(two);
children.add(three);
children.add(four);
root.setChildren(children);
children.remove(0);
children.remove(0);
children.remove(0);
children.add(five);
children.add(six);
two.setChildren(children);
children.remove(0);
children.remove(0);
children.add(ten);
children.add(eleven);
four.setChildren(children);
children.remove(0);
children.remove(0);
children.add(seven);
children.add(eight);
children.add(nine);
six.setChildren(children);
children.remove(0);
children.remove(0);
children.remove(0);
children.add(twelve);
ten.setChildren(children);
children.remove(0);
children.add(thirteen);
children.add(fourteen);
twelve.setChildren(children);
children.remove(0);
children.remove(0);
//---------------------------------------------------------------------
/*** DO NOT MAKE ANY CHANGE TO THE FOLLOWING CODE ***/
MyGenericTree<Integer> tree = new MyGenericTree<Integer>(root);
tree.traverseInPostOrder();
}
}
/*** DO NOT MAKE ANY CHANGE TO CLASS MyGenericTree EXCEPT THE PLACEHOLDER TO FILL IN ***/
/*** YOU CANNOT ADD A NEW FIELD VARIABLE ***/
/*** YOU CANNOT ADD A NEW METHOD DECLARATION ***/
class MyGenericTree<T> {
private TreeNode<T> root = null;
public MyGenericTree(TreeNode<T> root) {
this.root = root;
}
public void traverseInPostOrder() {
traverseInPostOrder(root);
}
public void traverseInPostOrder(TreeNode<T> node) {
//---------------------------------------------------------------------
System.out.println("1");
while(node.children.front != null) {
System.out.println(node.children.front);
node.children.remove(0);
}
/*
if(node.children == null){
System.out.print(node.data);
}
else{
TreeNode curr = node.children.get(0);
int i = 1;
while(curr != null) {
MyGenericTree<Integer> currNode = new MyGenericTree<Integer>(curr);
//curr = node.children.get(i);
currNode.traverseInPostOrder();
//curr = curr.next;\
i++;
}
System.out.print(node.data);
}
*/
//---------------------------------------------------------------------
}
}
/*** DO NOT MAKE ANY CHANGE TO CLASS TreeNode ***/
class TreeNode<N> {
N data = null;
TreeNode<N> parent = null;
MyGenericLinkedList<TreeNode<N>> children = null;
public TreeNode(N data) {
this.data = data;
}
public void setChildren(MyGenericLinkedList<TreeNode<N>> children) {
this.children = children;
}
}
/*** DO NOT MAKE ANY CHANGE TO CLASS MyGenericLinkedList ***/
class MyGenericLinkedList<S> {
Node<S> front;
public MyGenericLinkedList() {
front = null;
}
public void add(S value) {
if (front == null) {
front = new Node<S>(value);
} else {
Node<S> current = front;
while (current.next != null) {
current = current.next;
}
current.next = new Node<S>(value);
}
}
public S get(int index) {
Node<S> current = front;
for (int i = 0; i < index; i++) {
current = current.next;
}
return (S)current.data;
}
public void remove(int index) {
if (index == 0) {
front = front.next;
} else {
Node<S> current = front;
for (int i = 0; i < index - 1; i++) {
current = current.next;
}
current.next = current.next.next;
}
}
}
/*** DO NOT MAKE ANY CHANGE TO CLASS Node ***/
class Node<X> {
X data;
Node<X> next;
public Node(X data) {
this.data = data;
this.next = null;
}
public Node(X data, Node<X> next) {
this.data = data;
this.next = next;
}
}
Based on how you have the iterator, that can potentially destroy the linked list after having it print out. Generally, when working with linked lists, you want to keep the list. Below is the basic concept of iterating through a linked list.
while(node.children.front != null) {
System.out.println(node.children.front);
node.children.front = node.children.front.next
}
At any point, you only have access to single node, so if you want to go to the next node, you will have to set the current node to the next in the list. Since it might be null, that is why you'd have a conditional checking if the node is set to a null value. If it is set to a null value, you are at the end of the linked list.
I am learning java and i am still a beginner.i have written this code to implement a circular linked list and it keeps printing the numbers when i try to print the list. it looks like some kind of an infinite loop maybe. I even tried to use a debug but it didn't do much for me. I would very much appreciate it if you could review the code and see why this is happening. here is the code below. I would be also for giving me feedback on the code :)
this is the class for the circular linked list
public class CircularLinkedList<E> implements API<E> {
private Node<E> head;
private int size = 0;
public void placeAtBeginning(E element) {
Node<E> newNode = new Node<E>(element);
if(head == null) {
head = newNode;
head.setNext(head);
}else {
Node<E> temp = head;
head = newNode;
newNode.setNext(temp);
}
size++;
}
public void placeAtEnd(E element) {
Node<E> newNode = new Node<E>(element);
if (head == null) {
head = newNode;
}else {
Node<E> temp = head;
while (temp.getNext() != head) {
temp = temp.getNext();
}
temp.setNext(newNode);
}
newNode.setNext(head);
size++;
}
public void deleteFromBeginning() {
Node<E> temp = head;
while (temp.getNext() != head) {
temp = temp.getNext();
}
temp.setNext(head.getNext());
head = head.getNext();
size --;
}
public void deleteFromEnd() {
Node<E> temp = head;
while(temp.getNext().getNext() != head) {
temp = temp.getNext();
}
temp.setNext(head);
size--;
}
public void print() {
Node<E> temp = head;
while(temp.getNext()!= head) {
System.out.print(temp.getValue() + " , ");
temp = temp.getNext();
}
System.out.print(temp.getValue());
}
}
this is the class for my node
public class Node<T> {
private Node<T> next;
private T item;
public Node(T item) {
this.item = item;
}
public void setNext(Node<T> next) {
this.next = next;
}
public Node<T> getNext() {
return this.next;
}
public T getValue() {
return this.item;
}
}
this is my main where i tried to test it using int.
public class Main {
public static void main(String [] args) {
API <Integer> list = new CircularLinkedList<Integer>();
int a = 10;
int b = 3;
int c = 15;
int d = 8;
int f = 9;
list.placeAtBeginning(a);
list.placeAtEnd(b);
list.print();
System.out.println();
list.placeAtBeginning(c);
list.placeAtBeginning(d);
list.print();
}
}
this is my API which I used
public interface API <E> {
public void placeAtBeginning(E element);
public void placeAtEnd(E element);
public void deleteFromBeginning();
public void deleteFromEnd();
public void print();
}
Your method placeAtBeginning() doesn't insert the new element in the circular list but simply lets the next of the new element refer to the original circular list.
Try this:
public void placeAtBeginning(E element)
{
Node<E> newNode = new Node<E>(element);
if(head == null)
{
head = newNode;
head.setNext(head);
}
else
{
Node<E> last = head;
while (last.getNext() != head)
last = last.getNext();
newNode.setNext(head);
head = newNode;
last.setNext(head);
}
size++;
}
I didn't check the other methods. They might contain a similar error.
I am struggling to understand how to implement a remove(); for both a double and single linked class. I have figured out how to remove the first node in the double, but not in the single. First I would like to debug, problem solve the single linked class, then work on the double after that.
Here is the code I have so far for the Single Linked Class.
public class SingleLinkedClass<T> {
private Node <T> head;
private Node <T> tail;
private int size;
public SingleLinkedClass() {
size = 0;
head = null;
tail = null;
}
public void insertAtHead(T v)
{
//Allocate new node
Node newNode = new Node(v, head);
//Change head to point to new node
head = newNode;
if(tail == null)
{
tail = head;
}
//Increase size
size++;
}
public void insertAtTail(T v)
{
if(tail == null)
{
tail = new Node(v, null);
head = tail;
size++;
return;
}
Node newNode = new Node(v, null);
tail.nextNode = newNode;
tail = newNode;
size++;
}
public T removeHead()
{
if(head == null)
{
throw new IllegalStateException("list is empty! cannot delete");
}
T value = head.value;
head = head.nextNode;
size--;
return value;
}
public void removeTail()
{
//Case 1: list empty
if(head == null)
{
return;
}
//Case 2: list has one node
else if(head == tail)
{
head = tail = null;
}
else
{
Node temp = head;
while(temp.nextNode != tail)
{
temp = temp.nextNode;
}
tail = temp;
tail.nextNode = null;
}
size--;
}
public boolean remove(T v) {
Node<T> previous = head;
Node<T> cursor = head.nextNode;
if (head.nextNode == null) {
return false;
}
while(cursor != tail){
if (cursor.value.equals(v)) {
previous = cursor.nextNode;
return true;
}
previous = cursor;
cursor = cursor.nextNode;
}
return false;
}
public String toString() {
if (head == null) {
return "The list is Empty!";
}
String result = "";
Node temp = head;
while (temp != null) {
result += temp.toString() + " ";
temp = temp.nextNode;
}
return result;
}
public int size() {
return size;
}
private class Node <T> {
private T value;
private Node <T> nextNode;
public Node(T v, Node<T> n) {
value = v;
nextNode = n;
}
public String toString() {
return "" + value;
}
}
}
Here is my Double Linked Class
public class DoubelyLinkedList<E> {
private int size;
private Node<E> header;
private Node<E> trailer;
public DoubelyLinkedList() {
size = 0;
header = new Node<E>(null, null, null);
trailer = new Node<E>(null, null, header);
header.next = trailer;
}
public boolean remove(E v) {
//If the list is empty return false
if(header.next == trailer){
return false;
}
//If v is the head of the list remove and return true
Node <E> cursor = header.next;
for (int i = 0; i < size; i++) {
//Remove at Head
if(cursor.value.equals(v)){
removeAtHead();
}
cursor = cursor.next;
}
return true;
}
/*
} */
public void insertAtHead(E v) {
insertBetween(v, header, header.next);
}
public void insertAtTail(E v) {
insertBetween(v, trailer.prev, trailer);
}
private void insertBetween(E v, Node<E> first, Node<E> second) {
Node<E> newNode = new Node<>(v, second, first);
first.next = newNode;
second.prev = newNode;
size++;
}
public E removeAtHead() {
return removeBetween(header, header.next.next);
}
public E removeAtTail() {
return removeBetween(trailer.prev.prev, trailer);
}
private E removeBetween(Node<E> first, Node<E> second) {
if (header.next == trailer)// if the list is empty
{
throw new IllegalStateException("The list is empty!");
}
E result = first.next.value;
first.next = second;
second.prev = first;
size--;
return result;
}
public String toStringBackward() {
if (size == 0) {
return "The list is empty!";
}
String r = "";
Node<E> temp = trailer.prev;
while (temp != header) {
r += temp.toString() + " ";
temp = temp.prev;
}
return r;
}
public String toString() {
if (size == 0) {
return "The list is empty!";
}
String r = "";
Node<E> temp = header.next;
while (temp != trailer) {
r += temp + " ";
temp = temp.next;
}
return r;
}
private static class Node<T> {
private T value;
private Node<T> next;
private Node<T> prev;
public Node(T v, Node<T> n, Node<T> p) {
value = v;
next = n;
prev = p;
}
public String toString() {
return value.toString();
}
}
}
Here is my Driver
public class Driver {
public static void main(String[] args) {
DoubelyLinkedList<String> doubley = new DoubelyLinkedList();
SingleLinkedClass<String> single = new SingleLinkedClass();
single.insertAtHead("Bob");
single.insertAtHead("Sam");
single.insertAtHead("Terry");
single.insertAtHead("Don");
System.out.println(single);
single.remove("Bob");
System.out.println("Single Remove Head: " + single);
/*
single.remove("Don");
System.out.println("Single Remove Tail: " + single);
single.remove("Terry");
System.out.println("Single Remove Inbetween: " + single);
*/
System.out.println();
System.out.println();
doubley.insertAtHead("Bob");
doubley.insertAtHead("Sam");
doubley.insertAtHead("Terry");
doubley.insertAtHead("Don");
System.out.println(doubley);
doubley.remove("Bob");
System.out.println("Double Remove Head: " + doubley);
doubley.remove("Don");
System.out.println("Double Remove Tail: " + doubley);
/*
doubley.remove("Sam");
System.out.println("Double Remove Inbetween: " + doubley);
*/
}
}
In the removeHead moving head to its next, it might become null. Then tail was the head too. Then tail should be set to null too.
DoublyLinkedList is better English than DoubelyLinkedList.
As this is homework, I leave it by this.
Why isn't my insertLast(T data) method adding all of the elements into the list?
public class Tester {
public static void main(String[] args){
LinkedList<Integer> myList = new LinkedList<Integer>();
myList.insertLast(1);
myList.insertLast(2);
myList.insertLast(3);
myList.insertLast(4);
myList.insertLast(5);
myList.insertLast(6);
myList.displayList();
}
}
It adds only 6. What could be the problem with the code?
public class Node<T> {
public T data;
public Node<T> next;
public Node(T data, Node<T> n){
this.data = data;
this.next = n;
}
public void display(){
System.out.print(this.data + " ");
}
}
class LinkedList<T> implements Iterable<T>{
private Node<T> head;
private int size;
public LinkedList(){
this.head = new Node<T>(null, null);
this.size = 0;
}
public boolean isEmpty(){
return (head.next == null);
}
public void displayList(){
Node<T> current = head;
while(current != null){
current.display();
current = current.next;
}
}
public void insert(T data){
head = new Node<T>(data, null);
size++;
}
public void insertLast(T data){
Node<T> newNode = new Node<T>(data, null);
if(isEmpty()){
head = new Node<T>(data, null);
size++;
}
else{
Node<T> current = head;
while(current.next != null){
current = current.next;
}
current.next = newNode;
size++;
}
}
}
Every time you call insertLast, isEmpty returns true, because head.next is null. head.next is only ever set to non-null if isEmpty returns false.
This check:
if(isEmpty()){
head = new Node<T>(data, null);
size++;
}
initializes head to have a null next, so isEmpty() returns true everytime it's called. You need to check head itself to be null or not in isEmpty(), and in your constructor, instead of:
this.head = new Node<T>(null, null);
you should initialize it to:
this.head = null;
Hai Minor change in your program .You don't have to initialize head.next as null
import java.util.Iterator;
import java.util.Spliterator;
import java.util.function.Consumer;
public class Node<T> {
public T data;
public Node<T> next;
public Node(T data, Node<T> n){
this.data = data;
this.next = n;
}
public void display(){
System.out.print(this.data + " ");
}
}
class LinkedList<T> implements Iterable<T>{
private Node<T> head;
private int size;
public LinkedList(){
// this.head = new Node<T>(null, null);
this.size = 0;
}
public boolean isEmpty(){
return (head == null);
}
public void displayList(){
Node<T> current = head;
while(current != null){
current.display();
current = current.next;
}
}
public void insert(T data){
head = new Node<T>(data, null);
size++;
}
public void insertLast(T data){
Node<T> newNode = new Node<T>(data, null);
if(isEmpty()){
head = new Node<T>(data, null);
size++;
}
else{
Node<T> current = head;
while(current.next != null){
current = current.next;
}
current.next = newNode;
size++;
}
}
public void forEach(Consumer<? super T> arg0) {
// TODO Auto-generated method stub
}
public Iterator<T> iterator() {
// TODO Auto-generated method stub
return null;
}
public Spliterator<T> spliterator() {
// TODO Auto-generated method stub
return null;
}
}