Can the below design can be further optimized? I have used a hashmap and a Queue. SO space complexity will be O(n) and runtime will be O(n)
public class PrintAllRootToLeaves {
public static void print(BinaryTreeNode root) {
Queue nodesQ = new Queue();
HashMap hMap = new HashMap();
BinaryTreeNode head = root;
String tempVal ;
hMap.put(head,String.valueOf(head.getData()));
while (head != null) {
BinaryTreeNode left = head.getLeft();
BinaryTreeNode right = head.getRight();
if (left != null) {
if ((tempVal = (String) hMap.get(head)) != null) {
hMap.put(left,tempVal + left.getData());
}
nodesQ.enqueue(left);
}
if (right != null) {
if ((tempVal = (String) hMap.get(head)) != null) {
hMap.put(right,tempVal + right.getData());
}
nodesQ.enqueue(right);
}
if (right != null && left != null) {
hMap.remove(head);
}
head = (BinaryTreeNode) nodesQ.dequeue();
}
System.out.println("-----------Printing all routes ---------->" + hMap.values());
}
}
public class BinaryTree {
private class Node {
final int key;
final int value;
Node left;
Node Right;
public Node (Node node, int pKey, int qValue) {
key = pKey;
value = qValue;
if (node != null && node.key < pKey) {
left = node;
}
else if (node != null) {
Right = node;
}
}
}
public void preOrderTraversal(Node pNode,String path){
if (path == null) {
path = "";
}
if (pNode != null) {
path = path+" "+String.valueOf(pNode.key);
//If you remove the modulo check it will print all the paths.
if (pNode.key%5 == 0) {
System.out.println(path);
}
preOrderTraversal(pNode.left,path);
preOrderTraversal(pNode.Right,path);
}
}
/**
* #param args
*/
public static void main(String[] args) {
Node node1 = new BinaryTree().new Node(null, 5, 2);
Node node2 = new BinaryTree().new Node(null, 10, 25);
Node node3 = new BinaryTree().new Node(node1, 7, 50);
node3.Right = node2;
Node root = new BinaryTree().new Node(node3, 15, 6);
Node node4 = new BinaryTree().new Node(null, 30, 8);
Node node5 = new BinaryTree().new Node(node4, 20, 7);
root.Right = node5;
//This will print paths only divisable by 5
new BinaryTree().preOrderTraversal(root,null);
}
}
Related
In the spirit of How to repair a corrupted MPTT tree (nested set) in the database using SQL?, I am trying to figure out an algorithm to determine the left and right values of a Modified Preorder Tree Traversal in Java given a root Node. Does anyone have any experience converting a regular pre order traversal into the modified traversal?
I currently have this as my preorder traversal.
List<Node> preorderTraversal(Node root) {
List<Node> list = new ArrayList<>();
if(root == null) return list;
Stack<Node> stack = new Stack<>();
stack.push(root);
while(!stack.empty()) {
root = stack.pop();
list.add(root);
if(root.children != null) {
for(Node child : root.children) {
if(child != null) {
stack.push(child);
}
}
}
}
return list;
}
Firstly, your preorder traversal code traverses children in reverse order. When you push the children onto the stack in order, they get popped in reverse order, leading to incorrect behaviour. It should be something like this:
static List<Node> preorderTraversal(Node root) {
List<Node> list = new ArrayList<>();
if (root == null) return list;
Stack<Node> stack = new Stack<>();
stack.push(root);
while (!stack.empty()) {
root = stack.pop();
list.add(root);
if (root.children != null) {
// iterate in reverse
for (int i = root.children.size() - 1; i >= 0; i--) {
Node child = root.children.get(i);
if (child != null) {
stack.push(child);
}
}
}
}
return list;
}
Before we look at modified preorder traversal, it is helpful to look at how to implement preorder traversal recursively:
static List<Node> preorderTraversalRecursive(Node root) {
ArrayList<Node> outList = new ArrayList<>();
preorderTraversalRecursive(root, outList);
return outList;
}
private static void preorderTraversalRecursive(Node root, ArrayList<Node> outList) {
if (root == null) {
return;
}
outList.add(root);
if (root.children != null) {
for (Node child : root.children) {
preorderTraversalRecursive(child, outList);
}
}
}
This code simple outputs a node before traversing its children.
To make this into a modified preorder traversal, you only need to keep track of a counter that is incremented before and after every node is processed, and record it before and after the children are processed in order to get left and right values. Here, the current count is returned by the method so that it can be changed during processing of child nodes and this updated value used for their parents' right value:
static List<MPTTNode> modifiedPreorderTraversalRecursive(Node root) {
ArrayList<MPTTNode> outList = new ArrayList<>();
modifiedPreorderTraversalRecursive(root, 0, outList);
return outList;
}
private static int modifiedPreorderTraversalRecursive(Node root, int counter, ArrayList<MPTTNode> outList) {
if (root == null) {
return counter;
}
counter++;
MPTTNode mpttNode = new MPTTNode(root.data, counter, 0); // right value is unknown, leave as 0 for now
outList.add(mpttNode);
if (root.children != null) {
for (Node child : root.children) {
// modify counter
counter = modifiedPreorderTraversalRecursive(child, counter, outList);
}
}
counter++;
mpttNode.right = counter;
return counter;
}
This can also be implemented iteratively:
static List<MPTTNode> modifiedPreorderTraversal(Node root) {
List<MPTTNode> list = new ArrayList<>();
if (root == null) return list;
Stack<Node> stack = new Stack<>();
Stack<Integer> pending = new Stack<>();
stack.push(root);
int counter = 0;
while (!stack.empty()) {
root = stack.pop();
if (root == null) {
int nodeIndex = pending.pop();
counter++;
list.get(nodeIndex).right = counter;
continue;
}
counter++;
pending.push(list.size());
list.add(new MPTTNode(root.data, counter, 0)); // right value is unknown, leave as 0 for now
stack.push(null);
if (root.children != null) {
// iterate in reverse
for (int i = root.children.size() - 1; i >= 0; i--) {
Node child = root.children.get(i);
if (child != null) {
stack.push(child);
}
}
}
}
return list;
}
This works by using a pending stack to keep track of the indices of parent nodes within the output list (list). It uses null values in the stack stack to signal that all children of a node have been processed and so the right value of their parent is known.
Here's all my code, including the same example tree as is used in the linked question:
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class Main {
public static void main(String[] args) {
Node tree = new Node("Electronics",
Arrays.asList(
new Node("Televisions",
Arrays.asList(
new Node("Tube"),
new Node("LCD"),
new Node("Plasma")
)
),
new Node("Portable Electronics",
Arrays.asList(
new Node("MP3 Players", Collections.singletonList(
new Node("Flash")
)),
new Node("CD Players"),
new Node("2 Way Radios")
)
)
)
);
List<MPTTNode> list1 = Node.modifiedPreorderTraversal(tree);
List<MPTTNode> list2 = Node.modifiedPreorderTraversalRecursive(tree);
if (!list1.equals(list2)) {
throw new RuntimeException("Traversals not equal");
}
for (var node : list1) {
System.out.printf("%-30s left:%5d, right:%5d\n", node.data, node.left, node.right);
}
}
}
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
public class Node {
String data;
List<Node> children;
public Node(String data, List<Node> children) {
this.data = data;
this.children = children;
}
public Node(String data) {
this.data = data;
}
static List<Node> preorderTraversal(Node root) {
List<Node> list = new ArrayList<>();
if (root == null) return list;
Stack<Node> stack = new Stack<>();
stack.push(root);
while (!stack.empty()) {
root = stack.pop();
list.add(root);
if (root.children != null) {
// iterate in reverse
for (int i = root.children.size() - 1; i >= 0; i--) {
Node child = root.children.get(i);
if (child != null) {
stack.push(child);
}
}
}
}
return list;
}
static List<MPTTNode> modifiedPreorderTraversal(Node root) {
List<MPTTNode> list = new ArrayList<>();
if (root == null) return list;
Stack<Node> stack = new Stack<>();
Stack<Integer> pending = new Stack<>();
stack.push(root);
int counter = 0;
while (!stack.empty()) {
root = stack.pop();
if (root == null) {
int nodeIndex = pending.pop();
counter++;
list.get(nodeIndex).right = counter;
continue;
}
counter++;
pending.push(list.size());
list.add(new MPTTNode(root.data, counter, 0)); // right value is unknown, leave as 0 for now
stack.push(null);
if (root.children != null) {
// iterate in reverse
for (int i = root.children.size() - 1; i >= 0; i--) {
Node child = root.children.get(i);
if (child != null) {
stack.push(child);
}
}
}
}
return list;
}
static List<Node> preorderTraversalRecursive(Node root) {
ArrayList<Node> outList = new ArrayList<>();
preorderTraversalRecursive(root, outList);
return outList;
}
private static void preorderTraversalRecursive(Node root, ArrayList<Node> outList) {
if (root == null) {
return;
}
outList.add(root);
if (root.children != null) {
for (Node child : root.children) {
preorderTraversalRecursive(child, outList);
}
}
}
static List<MPTTNode> modifiedPreorderTraversalRecursive(Node root) {
ArrayList<MPTTNode> outList = new ArrayList<>();
modifiedPreorderTraversalRecursive(root, 0, outList);
return outList;
}
private static int modifiedPreorderTraversalRecursive(Node root, int counter, ArrayList<MPTTNode> outList) {
if (root == null) {
return counter;
}
counter++;
MPTTNode mpttNode = new MPTTNode(root.data, counter, 0);
outList.add(mpttNode);
if (root.children != null) {
for (Node child : root.children) {
counter = modifiedPreorderTraversalRecursive(child, counter, outList);
}
}
counter++;
mpttNode.right = counter;
return counter;
}
}
import java.util.Objects;
public class MPTTNode {
String data;
int left;
int right;
public MPTTNode(String data, int left, int right) {
this.data = data;
this.left = left;
this.right = right;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
MPTTNode mpttNode = (MPTTNode) o;
return left == mpttNode.left && right == mpttNode.right && Objects.equals(data, mpttNode.data);
}
}
Output:
Electronics left: 1, right: 20
Televisions left: 2, right: 9
Tube left: 3, right: 4
LCD left: 5, right: 6
Plasma left: 7, right: 8
Portable Electronics left: 10, right: 19
MP3 Players left: 11, right: 14
Flash left: 12, right: 13
CD Players left: 15, right: 16
2 Way Radios left: 17, right: 18
hi im new to codings and i have to print my binary search tree in a 2d model but this codes only print the orders of number in order(left-root-right) such as when i insert 10, 9, 11, 8, it will print inorder (left root right) = 8,9,10,11. what method or codes should i add to create a 2d tree here. sorry idk how to properly put the codes here just look at it like it is only a one code only.
class binarySearchTree {
class Node {
int key;
Node left, right;
int data;
public Node(int data){
key = data;
left = right = null;
}
}
// BST root node
Node root;
// Constructor for BST =>initial empty tree
binarySearchTree(){
root = null;
}
//delete a node from BST
void deleteKey(int key) {
root = delete_Recursive(root, key);
}
//recursive delete function
Node delete_Recursive(Node root, int key) {
//tree is empty
if (root == null) return root;
//traverse the tree
if (key < root.key) //traverse left subtree
root.left = delete_Recursive(root.left, key);
else if (key > root.key) //traverse right subtree
root.right = delete_Recursive(root.right, key);
else {
// node contains only one child
if (root.left == null)
return root.right;
else if (root.right == null)
return root.left;
// node has two children;
//get inorder successor (min value in the right subtree)
root.key = minValue(root.right);
// Delete the inorder successor
root.right = delete_Recursive(root.right, root.key);
}
return root;
}
int minValue(Node root) {
//initially minval = root
int minval = root.key;
//find minval
while (root.left != null) {
minval = root.left.key;
root = root.left;
}
return minval;
}
// insert a node in BST
void insert(int key) {
root = insert_Recursive(root, key);
}
//recursive insert function
Node insert_Recursive(Node root, int key) {
//tree is empty
if (root == null) {
root = new Node(key);
return root;
}
//traverse the tree
if (key < root.key) //insert in the left subtree
root.left = insert_Recursive(root.left, key);
else if (key > root.key) //insert in the right subtree
root.right = insert_Recursive(root.right, key);
// return pointer
return root;
}
void inorder() {
inorder_Recursive(root);
}
// recursively traverse the BST
void inorder_Recursive(Node root) {
if (root != null) {
inorder_Recursive(root.left);
System.out.print(root.key + " x ");
inorder_Recursive(root.right);
}
}
//PostOrder Traversal - Left:Right:rootNode (LRn)
void postOrder(Node node) {
if (node == null)
return;
// first traverse left subtree recursively
postOrder(node.left);
// then traverse right subtree recursively
postOrder(node.right);
// now process root node
System.out.print(node.key + " ");
}
// InOrder Traversal - Left:rootNode:Right (LnR)
void inOrder(Node node) {
if (node == null)
return;
//first traverse left subtree recursively
inOrder(node.left);
//then go for root node
System.out.print(node.key + " ");
//next traverse right subtree recursively
inOrder(node.right);
}
//PreOrder Traversal - rootNode:Left:Right (nLR)
void preOrder(Node node) {
if (node == null)
return;
//first print root node first
System.out.print(node.key + " ");
// then traverse left subtree recursively
preOrder(node.left);
// next traverse right subtree recursively
preOrder(node.right);
}
// Wrappers for recursive functions
void postOrder_traversal() {
postOrder(root); }
void inOrder_traversal() {
inOrder(root); }
void preOrder_traversal() {
preOrder(root); }
}
here i found this codes in stackoverflow, i want te output like this, i can use this but i dont know how can i make this as user input for the data and make it insert the integer into a tree not this manually inserted of the integer. thankyou very much to whoever put effort to understand my question and my situation as newbie.
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class BTreePrinterTest {
private static Node<Integer> test2() {
Node<Integer> root = new Node<Integer>(2);
Node<Integer> n11 = new Node<Integer>(3);
Node<Integer> n12 = new Node<Integer>(5);
Node<Integer> n21 = new Node<Integer>(2);
Node<Integer> n22 = new Node<Integer>(6);
Node<Integer> n23 = new Node<Integer>(9);
Node<Integer> n31 = new Node<Integer>(5);
root.left = n11;
root.right = n12;
n11.left = n21;
n11.right = n22;
n12.left = n23;
n12.right = n31;
return root;
}
public static void main(String[] args) {
BTreePrinter.printNode(test2());
}
}
class Node<T extends Comparable<?>> {
Node<T> left, right;
T data;
public Node(T data) {
this.data = data;
}
}
class BTreePrinter {
public static <T extends Comparable<?>> void printNode(Node<T> root) {
int maxLevel = BTreePrinter.maxLevel(root);
printNodeInternal(Collections.singletonList(root), 1, maxLevel);
}
private static <T extends Comparable<?>> void printNodeInternal(List<Node<T>> nodes, int level, int maxLevel) {
if (nodes.isEmpty() || BTreePrinter.isAllElementsNull(nodes))
return;
int floor = maxLevel - level;
int endgeLines = (int) Math.pow(2, (Math.max(floor - 1, 0)));
int firstSpaces = (int) Math.pow(2, (floor)) - 1;
int betweenSpaces = (int) Math.pow(2, (floor + 1)) - 1;
BTreePrinter.printWhitespaces(firstSpaces);
List<Node<T>> newNodes = new ArrayList<Node<T>>();
for (Node<T> node : nodes) {
if (node != null) {
System.out.print(node.data);
newNodes.add(node.left);
newNodes.add(node.right);
} else {
newNodes.add(null);
newNodes.add(null);
System.out.print(" ");
}
BTreePrinter.printWhitespaces(betweenSpaces);
}
System.out.println("");
for (int i = 1; i <= endgeLines; i++) {
for (int j = 0; j < nodes.size(); j++) {
BTreePrinter.printWhitespaces(firstSpaces - i);
if (nodes.get(j) == null) {
BTreePrinter.printWhitespaces(endgeLines + endgeLines + i + 1);
continue;
}
if (nodes.get(j).left != null)
System.out.print("/");
else
BTreePrinter.printWhitespaces(1);
BTreePrinter.printWhitespaces(i + i - 1);
if (nodes.get(j).right != null)
System.out.print("\\");
else
BTreePrinter.printWhitespaces(1);
BTreePrinter.printWhitespaces(endgeLines + endgeLines - i);
}
System.out.println("");
}
printNodeInternal(newNodes, level + 1, maxLevel);
}
private static void printWhitespaces(int count) {
for (int i = 0; i < count; i++)
System.out.print(" ");
}
private static <T extends Comparable<?>> int maxLevel(Node<T> node) {
if (node == null)
return 0;
return Math.max(BTreePrinter.maxLevel(node.left), BTreePrinter.maxLevel(node.right)) + 1;
}
private static <T> boolean isAllElementsNull(List<T> list) {
for (Object object : list) {
if (object != null)
return false;
}
return true;
}
}
btw im learning this by my own, i tried merging the two codes but it gives me error i cant fix it.
I should have not made the whole exercise for you, so please try to understand the code. Tell me if something is not clear for you.
public static void main(String[] args) throws IOException {
System.out.println("Write your input");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String lines = br.readLine();
binarySearchTree b = new binarySearchTree();
b.input(lines);
b.print();
}
These functions go to binarySearchTree.
protected void printRecursive(Node node, int depth) {
System.out.println("");
for(int i = 0; i<depth; i++) {
System.out.print(" ");
}
System.out.print(node.key);
if(node.left != null) {
printRecursive(node.left, depth + 1);
}
if(node.right != null) {
printRecursive(node.right, depth + 1);
}
}
public void input(String s) throws IOException {
String[] strs = s.trim().split("\\s+");
for (int i = 0; i < strs.length; i++) {
insert(Integer.parseInt(strs[i]));
}
}
Also i used this answer in my code.
Hello i have an Assignment to modify a java program :
1- Makeing the Append operation be always in the front of the List :
LinkedList myList = new LinkedList(5);
myList.append(7);
myList.print();
it should be like this :
7 -> 5 -> null
instead of :
5 -> 7 -> null
2- Insert operation will be always as follows: any new added element using insert operation
should be after the current maximum element in the List
LinkedList myList = new LinkedList(2);
myList.append(5);
myList.insert(1);
myList.insert(4);
myList.print();
it should be :
5 -> 4 -> 1 -> 2 -> null
instead of :
5 -> 4 -> 2 -> 1 -> null
here is the code
class Node {
Node next;
int num ;
public Node(int val) {
num = val;
next = null;
}
}
public class LinkedList {
Node head;
public LinkedList(int val) {
head = new Node(val);
}
public void append(int val) {
Node tmpNode = new Node(val);
tmpNode.num = val;
tmpNode.next = head;
head = tmpNode;
}
public void insert(int val) {
Node currentNode = head;
Node nextNode = head.next;
if (currentNode.num < val) {
Node tmpNode = head;
head = new Node(val);
head.next = tmpNode;
return;
}
if (nextNode != null && nextNode.num < val) {
currentNode.next = new Node(val);
currentNode.next.next = nextNode;
return;
}
while (nextNode != null && nextNode.num < val) {
currentNode = nextNode;
nextNode = nextNode.next;
}
currentNode.next = new Node(val);
currentNode.next.next = nextNode;
}
public void delete(int val) {
Node prevNode = null;
Node currNode = head;
if (head.num == val) {
head = head.next;
return;
}
while (currNode != null && currNode.num != val) {
prevNode = currNode;
currNode = currNode.next;
}
if (currNode == null) {
System.out.println("A node with that value does not exist.");
} else {
prevNode.next = currNode.next;
}
}
public void print() {
Node tmpNode = head;
while (tmpNode != null) {
System.out.print(tmpNode.num + " -> ");
tmpNode = tmpNode.next;
}
System.out.print("null" + "\n");
}
public static void main(String[] args) {
LinkedList myList = new LinkedList(2);
myList.append(5);
myList.insert(10);
myList.insert(4);
myList.print();
}
}
I have tried to do it but i am not sure i did it right
Thanks for your time !
I googled this, but all of them are talking "swap nodes without swapping data".
I tried to write a swap node method myself:
public void swapNodes(int num1, int num2) {
if(num1 == num2) {
return;
}
Node currentNum1 = head;
Node currentNum2 = head;
Node waitForSwap1 = null;
Node waitForSwap2 = null;
while (currentNum1 != null) {
if (currentNum1.data == num1) {
waitForSwap1 = currentNum1;
System.out.println();
System.out.println("waitForSwap 1");
System.out.println(waitForSwap1.data);
}
currentNum1 = currentNum1.next;
}
while (currentNum2 != null) {
if (currentNum2.data == num2) {
waitForSwap2 = currentNum2;
System.out.println("waitForSwap 2");
System.out.println(waitForSwap2.data);
}
currentNum2 = currentNum2.next;
}
currentNum1 = waitForSwap2;
currentNum2 = waitForSwap1;
System.out.println("currentNum1");
System.out.println(currentNum1.data);
System.out.println("currentNum2");
System.out.println(currentNum2.data);
}
Here's the result
As you can see, currentNum1 and currentNum2 changed to each other, but the printed result is not swapped. How do I swap two nodes and their data?
Edit: the complete example below
Node Class
public class Node {
public int data;
public Node next;
public Node(int _data) {
this.data = _data;
this.next = null;
}
public String toString() {
return (Integer.toString(data));
}
}
Linked List Class
public class LinkedList {
Node head;
public void Insert(int data) {
Node node = new Node(data);
if (head == null) {
head = node;
} else {
Node n = head;
while (n.next != null) {
n = n.next;
}
n.next = node;
}
}
public void ShowList() {
Node node = head;
while (node != null) {
System.out.print(node.data + " ");
node = node.next;
}
}
public void swapNodes(int num1, int num2) {
if (num1 == num2) {
return;
}
Node currentNum1 = head;
Node currentNum2 = head;
Node waitForSwap1 = null;
Node waitForSwap2 = null;
while (currentNum1 != null) {
if (currentNum1.data == num1) {
waitForSwap1 = currentNum1;
System.out.println();
System.out.println("waitForSwap 1");
System.out.println(waitForSwap1.data);
}
currentNum1 = currentNum1.next;
}
while (currentNum2 != null) {
if (currentNum2.data == num2) {
waitForSwap2 = currentNum2;
System.out.println("waitForSwap 2");
System.out.println(waitForSwap2.data);
}
currentNum2 = currentNum2.next;
}
currentNum1 = waitForSwap2;
currentNum2 = waitForSwap1;
System.out.println("currentNum1");
System.out.println(currentNum1.data);
System.out.println("currentNum2");
System.out.println(currentNum2.data);
}
}
Tester
public class Runner {
public static void main(String[] args) {
LinkedList lkdList = new LinkedList();
lkdList.Insert(10);
lkdList.Insert(9);
lkdList.Insert(15);
lkdList.Insert(2);
lkdList.Insert(73);
lkdList.ShowList();
lkdList.swapNodes(10, 2);
System.out.println();
System.out.println("After Swap");
lkdList.ShowList();
}
}
Ok, if you only want to swap data, not nodes, here it is:
public void swapNodes(int num1, int num2) {
if (num1 == num2) {
return;
}
Node node1 = null;
Node node2 = null;
Node cur = head;
while(cur != null) {
if (num1 == cur.data) {
node1 = cur;
}
if (num2 == cur.data) {
node2 = cur;
}
cur = cur.next;
}
if (node1 == null || node2 == null)
return;
int tmp = node1.data;
node1.data = node2.data;
node2.data = tmp;
}
public class doubleLinkedList {
class Node {
String value;
Node prev;
Node next;
Node(String val, Node p, Node n) {
value = val;
prev = p;
next = n;
}
Node(String val) {
value = val;
prev = null;
next = null;
}
}
Node first;
Node last;
public doubleLinkedList() {
first = null;
last = null;
}
public boolean isEmpty() {
if (first == null)
return true;
else
return false;
}
/**The size method returns the length of the linked list
* #return the number of element in the linked list
*/
public int size() {
int count = 0;
Node traverse = first;
while (traverse != null) {
count++;
traverse = traverse.next;
}
return count;
}
public void add(String element) {
if (isEmpty()) {
first = new Node(element);
last = first;
} else {
Node p = first;
Node elementTobeAdded;
while (((p.value).compareTo(element)) > 0 && p.next != null) {
p = p.next;
}
if (p.next != null) {
elementTobeAdded = new Node(element, p, p.next);
p.next.prev = elementTobeAdded;
p = elementTobeAdded.prev;
} else {
elementTobeAdded = new Node(element, p, null);
p.next = elementTobeAdded;
elementTobeAdded.next = null;
last = elementTobeAdded;
}
}
}
public void printForward() {
Node printNode = first;
while (printNode != null) {
System.out.print(printNode.value + ", ");
printNode = printNode.next;
}
}
}
public class test {
public static void main(String[] args) {
doubleLinkedList car = new doubleLinkedList();
car.add("Jeep");
car.add("benz");
car.add("Honda");
car.add("Lexus");
car.add("BMW");
car.printForward();
}
}
My add method is trying to add nodes to a list in alphabetical order. My printForward method prints out each element in the list.
In my main method, it prints out "Jeep, benz, Honda, BMW,", which is not in alphabetical order.
Change the not empty case for your add method from this
Node p = first;
Node elementTobeAdded;
while(((p.value).compareTo(element)) > 0 && p.next != null)
{
p = p.next;
}
if(p.next != null)
{
elementTobeAdded = new Node(element,p,p.next);
p.next.prev = elementTobeAdded;
p = elementTobeAdded.prev;
}
else
{
elementTobeAdded = new Node(element, p, null);
p.next = elementTobeAdded;
elementTobeAdded.next = null;
last = elementTobeAdded;
}
to this:
Node p = first;
while (p.value.compareTo(element) < 0 && p.next != null) {
p = p.next;
}
if (p.value.compareTo(element) > 0) {
Node toAdd = new Node(element, p.prev, p);
p.prev = toAdd;
if (toAdd.prev != null) {
toAdd.prev.next = toAdd;
}else {
first = toAdd;
}
}else {
Node toAdd = new Node(element, p, p.next);
p.next = toAdd;
if (toAdd.next != null) {
toAdd.next.prev = toAdd;
}else {
last = toAdd;
}
}
There were many errors here. The biggest one was that you never checked for the case where the new element should be inserted at the beginning of the list. A new element was always inserted after the first element even if it should have come first.
Note that "benz" comes at the end because the String.compareTo method treats capitals as coming before lower case letters.
It is not an a linked list... You wrote some sort of Queue (with optional possibility to make it Dequeue).
About your question - you have an error in your 'add' method - at least you don't check if it is necessary to move head forward. It is possible that you have another bugs, but it is too hard to read such styled sources (please fix your question formatting)...