How do I insert one Node-chain into another node-chain - java

Good evening, I have a question. I have a Node class that I created:
public class Node {
private int value;
private Node next;
private Node prev;
Node(int value) {
this.value = value;
this.next = null;
}
Node(int value, Node next) {
this.value = value;
this.next = next;
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
public Node getNext() {
return next;
}
public void setNext(Node next) {
this.next = next;
}
public void printXXX() {
System.out.println("Node : " + this.value);
}
public boolean hasNext() {
if(this.next != null) {
return true;
} else {
return false;
}
}
And I have a task to print a new Node chain where I need to insert one Node-chain into another Node-chain somewhere in the middle using a function. For example Node1[25,28,32,39,60,70] Node2[43,49,52,58] and I want a function to return Node[25,28,32,39,43,49,52,58,60,70]
I have a code shown here:
public class Main {
public static void createANewChain(Node node1, Node node2) {
boolean flag = false;
while(node1.getNext() != null) {
if(node1.getNext().getValue()>node2.getValue()) {
node1.setNext(node2);
flag = true;
while (node2.getNext() != null) {
node2 = node2.getNext();
}
//node2.setNext(node1.getNext()); //error
}
else
{
node1 = node1.getNext();
}
}
if(flag == false) {
while(node1.getNext() != null) {
node1 = node1.getNext();
}
node1.setNext(node2);
}
}
public static void printANewChain(Node node1) {
while(node1.hasNext()) {
System.out.println(node1.getValue());
node1 = node1.getNext();
}
System.out.println(node1.getValue());
}
public static void main(String[] args) {
Node n6 = new Node(70);
Node n5 = new Node(60,n6);
Node n4 = new Node(39,n5);
Node n3 = new Node(32,n4);
Node n2 = new Node(28,n3);
Node n1 = new Node(25,n2);
Node g4 = new Node(58);
Node g3 = new Node(52,g4);
Node g2 = new Node(49,g3);
Node g1 = new Node(45,g2);
createANewChain(n1,g1);
printANewChain(n1);
}
}
In the end, I get an infinite loop. So, the problem is that after linking the first Node to the second I lose all those parts of a chain that were supposed to go after linking Node2
Node1[25,28,32,39] ... [60,70] - I lose them
In the task, all numbers from Node2 should be in the gasp between two specific numbers in Node1
Please, help me to find a solution on how to link two of these Nodes. I hope I explained the task clearly.
Have a nice day and thanks for your solutions.

It is simpler than this. But first, your function definition isn't right. You need to specify which node to append to, and which to insert, like
public static void createANewChain(Node nodeToAppendTo, Node nodeToInsert) {
Then, what you need to do is
set the node following nodeToAppendTo previous value (nodeToAppend.next.prev) to nodeToInsert's last element, and vice versa (nodeToInsert last element . next = node following nodeToAppendTo, and set nodeToAppendTo's last element likewise)
Then set nodeToAppendTo.next to nodeToInsert, and nodeToInsert.previous to nodeToAppendTo
This is how you insert one linked list into another.
Because I think this is a homework problem, I have left it for you to code up what I have pseudo-coded

Thank you for your answer, I solved this problem by myself Idk whether it's a bad or good algorithm.
public static void createANewChain(Node node1, Node node2) {
boolean flag = false;
while(node1.getNext() != null) {
if(node1.getNext().getValue()>node2.getValue()) {
Node copy = node2;
while (copy.getNext() != null) {
copy = copy.getNext();
}
copy.setNext(node1.getNext());
node1.setNext(node2);
flag = true;
while (node2.getNext() != null) {
node2 = node2.getNext();
}
}
else
{
node1 = node1.getNext();
}
}
if(flag == false) {
while(node1.getNext() != null) {
node1 = node1.getNext();
}
node1.setNext(node2);
}
}

Related

Add and Print new Nodes

I was working on a program to add nodes to a list, but I seem to be doing something wrong...
My java program has three Classes; Demo, Lista and Node
Class Node:
public class Node {
private int num;
private Node tail;
private Node head;
public Node (int num, Node head, Node tail) {
this.num = num;
this.head = head;
this.tail = tail;
}
}
Class Lista:
public class Lista {
private Node nil;
public Lista () {
nil = null;
}
public void add (int num) {
Node newNode = new Node(num, head, tail);
if (head == null) {
head = newNode;
tail = newNode;
}
}
public void display () {
Node current = head;
while(current != null) {
System.out.print(current.num);
}
}
}
Class Demo:
public class Demo {
public static void main ( String [] args) {
Lista lista = new Lista();
lista.add(3);
lista.add(9);
lista.add(7);
lista.display();
}
}
Demo class is to add the different nodes to the list "lista". Class Node has num, head which is the next one and tail which is the previous one. How can I go about getting Class Lista to be able to use head and tail from Class Node? And if it is possible would this code work when running Demo? What should I change/modify to get this to work?
You may want to modify your code something like this:
EDIT - This is a doubly-linked list implementation.
class Node {
int num;
Node prev;
Node next;
Node(int num) {
this.num = num;
}
Node(int num, Node prev, Node next) {
this.num = num;
this.prev = prev;
this.next = next;
}
void setPrev(Node prev) {
this.prev = prev;
}
void setNext(Node next) {
this.next = next;
}
}
class Lista {
Node root;
Node endNode;
public void add(int num) {
Node n = new Node(num);
if (root == null) {
root = n;
} else {
n.setPrev(endNode);
endNode.setNext(n);
}
endNode = n;
}
public void display() {
Node iterateeNode = root;
while (iterateeNode != null) {
System.out.print(iterateeNode.num + " ");
iterateeNode = iterateeNode.next;
}
}
}
The selected answer is technically not correct. For a (single) Linked List, all your Lista need is a single (head) node. Additionally, the Node class needs a single (next) Node field.
The following is a potential implementation of Node:
public class Node {
private Node next;
private int value;
public Node(int value) {
this.value = value;
}
public boolean hasNext() {
return next != null;
}
public Node next() {
return next;
}
public void add(Node node) {
if (next == null) {
next = node;
} else {
Node temp = next;
while (temp != null) {
temp = temp.next;
}
temp = node;
}
}
#Override
public String toString() {
return String.valueOf(value);
}
}
The add() method will insert the new node in next if it is null. Otherwise, it will traverse the nodes until it finds the tail node (the one where next is null).
The Lista has only the first element in the list (head node).
public class Lista {
private Node head;
public void add(Node node) {
if (head == null) {
head = node;
} else {
Node temp = head;
while (temp.hasNext()) {
temp = temp.next();
}
temp.add(node);
}
}
// Other methods
}
When the add() function in the list is called, it will either add the new node as the head (if the list doesn't have one already) or rely on the already added nodes to figure out where the end of the list is in order to insert the new node.
Lastly, to display the list, just override the toString() method in node and add the "toString" value to a string buffer and send the concatenated string value to the console similar to the the code below.
public void display() {
StringBuilder buff = new StringBuilder("[");
buff.append(head);
if (head != null) {
Node next = head.next();
buff.append(",");
while (next != null) {
buff.append(next);
next = next.next();
buff.append(",");
}
}
buff.append("]");
int idx = buff.lastIndexOf(",");
buff.replace(idx, idx+1, "");
System.out.println(buff.toString());
}
Executing the following displays [3,9,7] as expected.
public class Demo {
public static void main ( String [] args) {
Lista lista = new Lista();
lista.add(new Node(3));
lista.add(new Node(9));
lista.add(new Node(7));
lista.display();
}
}

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

How to remove from a Linked list in Java?

So I wrote my own linked list (and list node) in Java as a part of a homework.
Now, I'm trying to erase entries, but the function is not working.
I know the concept:
Search for node keeping the previous;
Tell previous node to point to next node;
Return or stop using the node so GC erases it.
For some reason it is not working. I can delete the node with the same value over and over. I'm afraid it is something related to Java pointers.
The code:
Node:
public class SimpleNode<E> {
private E value;
private SimpleNode<E> next;
public SimpleNode() {
this.value = null;
this.next = null;
}
public NoSimples(E data, SimpleNode<E> ref) {
this.value = data;
this.next = ref;
}
// Getters and Setters
}
List:
public class LinkedList<E> implements Iterable<SimpleNode<E>> {
private SimpleNode<E> head;
private int size = 0;
public LinkedList() {
this.head = new SimpleNode<E>();
}
public void add(SimpleNode<E> node) {
this.addFirst(node.getValue());
}
public void addFirst(E item) {
SimpleNode<E> nonde = new SimpleNode<E>(item, this.head);
this.head = node;
size++;
}
public void add(E value) {
this.addFirst(value);
}
public SimpleNode<E> removeFirst() {
SimpleNode<E> node = this.head;
if (node == null) {
return null;
} else {
this.head = node.getNext();
node.setNext(null);
this.size--;
return node;
}
}
public SimpleNodes<E> remove(E value) {
SimpleNode<E> nodeAnt = this.head;
SimpleNode<E> node = this.head.getNext();
while (node != null) {
if (node.getValue()!= null && node.getValue().equals(value)) {
nodeAnt.setNext(node.getNext());
node.setNext(null);
return node;
}
nodeAnt = node;
node = node.getNext();
}
return null;
}
// Other irrelevant methods.
}
Multiple Problems :
Think if you have a list 1,2,3,4. Now, if you try to remove 1, your code fails.
nodeAnt = node should be nodeAnt = nodeAnt.getNext(). Remember, the're all references, not Objects
Also, a recursive way might be easier to understand. For example, Here is how I implemented it
public void remove(E e){
prev = head;
removeElement(e, head);
System.gc();
}
private void removeElement(E e, Node currentElement) {
if(currentElement==null){
return;
}
if(head.getData().equals(e)){
head = head.getNext();
size--;
}else if(currentElement.getData().equals(e)){
prev.setNext(currentElement.getNext());
size--;
}
prev = prev.getNext();
removeElement(e, currentElement.getNext());
}
Note: I delete all occurrences of the Element, as I needed it. You may need it to be different.

How to remove all evens in linked list java

How can I remove all the evens in a linked list in java? Other similar questions did not help me. I have a possible solution, but it seems too complicated. I'm not sure it even works.
public class Node {
public int value;
public Node next;
public Node (int val) {
value = val;
}
public Node removeNode (Node root) {
if (root == null || (root.next == null && isOdd(root.value))) {
return null;
}
Node deep = root;
while (deep.next != null) {
deep = deep.next;
}
if (isOdd(deep.value)) {
for (Node x = root; x != null; x = x.next) {
if (isOdd(x.next.value)) {
x.next = x.next.next;
}
}
} else {
for (Node x = root; x.next != null; x = x.next) {
if (isOdd(x.next.value)) {
x.next = x.next.next;
}
}
}
if (isOdd(root.value)) {
root = root.next;
}
return root;
}
public boolean isOdd (int val) {
return (val % 2 == 1);
}
How can I improve this solution?
First of all: The remove method should be in your LinkedList class, not in the Node class itself!
After that it's quite easy to just remove the the even ones:
public class LinkedList {
private Node root;
public void removeEvens() {
if (root == null) return;
// removing all even nodes after the root
Node prev = root;
while (prev.next != null) {
if (isEven(prev.next))
prev.next = prev.next.next; // next is even: delete it
else
prev = prev.next; // next is not even: proceed
}
// delete root if it's even
if (isEven(root))
root = root.next;
}
private boolean isEven(Node node) {
return node.value % 2 == 0;
}
}
You can add an element before root node. In that case you don't have to write code for check root node.
public class Node {
public int value;
public Node next;
public Node(){}
public Node (int val) {
value = val;
}
public static Node removeEvens (Node root) {
Node head = new Node();
head.next = root;
for (Node node = head; node.next!=null; node=node.next)
if (isEven(node.next))
node.next = node.next.next;
return head.next;
}
public static boolean isEven(Node node) {
return node.value % 2 == 0;
}
}

Inserting at the end of a LinkedList

public class LinkedList<T>
{
private Node head;
private int size;
public LinkedList()
{
}
public void addToHead(T value) // create new node, make new node point to head, and head point to new node
{
if (head == null)
{
head = new Node(value,null);
}
else
{
Node newNode = new Node(value,head);
head = newNode;
}
size++;
}
public boolean isEmpty()
{
return head == null;
}
public int size()
{
return size;
}
public void removeHead()
{
head = head.next;
size--;
}
public void addToTail(T value)
{
if (isEmpty())
{
System.out.println("You cannot addtoTail of a emptyList!");
}
else
{
System.out.println(value);
Node current = head;
System.out.println("we are pointing to head: "+current);
while (current.getNext() != null) // loop till the end of the list (find the last node)
{
System.out.println("we are now pointing to: "+current.getElement());
current = current.getNext();
}
System.out.println("We are at the last node:"+current); // its working
System.out.println("it should point to null:"+current.getNext()); // its working
current.setNext(new Node(value,null)); // make it point to our new node we want to insert
System.out.println(current.getNext()); // it is pointing to the new node.. yet the node is not actually inserted (local variable problem? )
size++;
}
}
public String toString()
{
String output = "";
if (!isEmpty())
{
Node current = head;
output = "";
while (current.getNext() != null)
{
output += current.toString()+ "->";
current = current.getNext();
}
}
return output;
}
protected class Node
{
private T element;
private Node next;
public Node()
{
this(null,null);
}
public Node(T value, Node n)
{
element = value;
next = n;
}
public T getElement()
{
return element;
}
public Node getNext()
{
return next;
}
public void setElement(T newElement)
{
element = newElement;
}
public void setNext(Node newNext)
{
next = newNext;
}
public String toString()
{
return ""+element;
}
}
}
So I have written this linkedlist class, and every method works except addtoTail. For example say I create a instance of my linkedlist class, and call addToHead(5), then addtoTail(6) and use my toString method to print out the linkedlist, it only contains 5->. I debugged the addToTail and everything seems to be pointing to the correct locations, yet for some reason it does not add the new node (6) to the list. Hopefully I explained that clearly. I am probably missing something really simple (I even drew it on paper to visualize it but do not see the problem).
Your addToTail function is probably fine. I think the culprit is your toString function. In particular, in this snippet:
while (current.getNext() != null)
{
output += current.toString()+ "->";
current = current.getNext();
}
Your condition terminates the loop before reaching the end. What you actually want is:
while(current != null) {
....
}

Categories

Resources