Check if subtree? - java

Given two binary trees with head reference as T and S having at most N nodes. The task is to check if S is present as subtree in T.
A subtree of a tree T1 is a tree T2 consisting of a node in T1 and all of its descendants in T1.
Why my approach is fail?
my algo is :-
Find inorder and preorder traversals of T, store them in two lists.
Find inorder and preorder traversals of S, store them in two lists.
If inorder and preorder lists of T occurs in inorder and preorder lists of S then return true else false.
import java.util.LinkedList;
import java.util.Queue;
import java.io.*;
import java.util.*;
class Node{
int data;
Node left;
Node right;
Node(int data){
this.data = data;
left=null;
right=null;
}
}
class GfG {
static Node buildTree(String str){
if(str.length()==0 || str.charAt(0)=='N'){
return null;
}
String ip[] = str.split(" ");
// Create the root of the tree
Node root = new Node(Integer.parseInt(ip[0]));
// Push the root to the queue
Queue<Node> queue = new LinkedList<>();
queue.add(root);
// Starting from the second element
int i = 1;
while(queue.size()>0 && i < ip.length) {
// Get and remove the front of the queue
Node currNode = queue.peek();
queue.remove();
// Get the current node's value from the string
String currVal = ip[i];
// If the left child is not null
if(!currVal.equals("N")) {
// Create the left child for the current node
currNode.left = new Node(Integer.parseInt(currVal));
// Push it to the queue
queue.add(currNode.left);
}
// For the right child
i++;
if(i >= ip.length)
break;
currVal = ip[i];
// If the right child is not null
if(!currVal.equals("N")) {
// Create the right child for the current node
currNode.right = new Node(Integer.parseInt(currVal));
// Push it to the queue
queue.add(currNode.right);
}
i++;
}
return root;
}
static void printInorder(Node root){
if(root == null)
return;
printInorder(root.left);
System.out.print(root.data+" ");
printInorder(root.right);
}
public static void main (String[] args) throws IOException {
BufferedReader br= new BufferedReader(new InputStreamReader(System.in));
int t=Integer.parseInt(br.readLine());
while(t-- > 0){
String tt= br.readLine();
Node rootT = buildTree(tt);
String s= br.readLine();
Node rootS = buildTree(s);
// printInorder(root);
Solution tr=new Solution();
boolean st=tr.isSubtree(rootT, rootS);
if(st==true){
System.out.println("1");
}else{
System.out.println("0");
}
}
}
}// } Driver Code Ends
class Solution {
// algo implementation is started from here.
public static void preorder(Node root , ArrayList<Integer>al )
{
if(root!=null)
{
al.add(root.data);
preorder(root.left, al);
preorder(root.right, al);
}
}
public static void inorder(Node root, ArrayList<Integer>al)
{
if(root!=null)
{
inorder(root.left, al);
al.add(root.data);
inorder(root.right, al);
}
}
public static boolean isSubtree(Node t, Node s)
{
ArrayList<Integer> alt1 = new ArrayList<>();
ArrayList<Integer>alt2 = new ArrayList<>();
ArrayList<Integer> als1 = new ArrayList<>();
ArrayList<Integer>als2 = new ArrayList<>();
preorder(t,alt1);
inorder(t,alt2);
preorder(s,als1);
inorder(s,als2);
if(alt1.containsAll(als1) && alt2.contains(als2))
return true;
return false;
}
}
~~~

you approch is right, you are checking is arraylist of S has all the values present in array list of T
just change this part
als1.containsAll(alt1) && als2.contains(alt2) to if(alt1.containsAll(als1) && alt2.contains(als2)) return true;

Related

How do I print topological sort and also detect cycles?

I am using a method DFS which marks the visited node as visited and puts the string into the result stack.
This is a DAG which mean two Nodes can point to the same node as long as its not pointing back and creating a cycle. I created a Test case to create a cycle.
I am pointing a -> b -> c -> d -> e then I point z -> d and z -> d and then z -> a
I am pretty sure the culprit is the DFS algo called dfs. I have tried changing it but I am having a hard time figuring out the logic.
I node has a boolean called visited which I set to true and the I set to false after I have traversed its children. If I end up running into a true node then I print cyclic and end the program.
I am looking for guidance on a better way to implement this exact problem. Is there logical error in my dfs? I think thats where the problem lies.
package ChaseInterview;
import java.util.*;
public class ChaseInterview {
public static class Node<T> {
T val;
HashSet<Node<T>> adj = new HashSet<>();
boolean visited = false;
public Node(T val) {
this.val = val;
}
public Node() {
}
#Override
public String toString() {
return val.toString() + adj.toString();
}
}
public static class DAG<T> {
Node<T> root = new Node<T>();
HashMap<T, Node<T>> map = new HashMap<>();
public void DAG() {
}
public void add(T val) {
if (map.containsKey(val)) return;
Node<T> newNode = new Node<T>(val);
map.put(val, newNode);
root.adj.add(newNode);
}
public void add(T val1, T val2) {
Node<T> node1 = map.containsKey(val1) ? map.get(val1) : new Node<T>(val1);
Node<T> node2 = map.containsKey(val2) ? map.get(val2) : new Node<T>(val2);
if (!map.containsKey(val1)) root.adj.add(node1);
if (root.adj.contains(node2)) root.adj.remove(node2);
node1.adj.add(node2);
map.put(val1, node1);
map.put(val2, node2);
}
public String print() {
Stack<T> stack = new Stack<>();
dfs(stack, root);
StringBuilder res = new StringBuilder();
while (!stack.isEmpty()) {
res.append(stack.pop());
}
return res.reverse().toString();
}
public void dfs(Stack<T> stack, Node<T> root) {
if (root.visited) {
System.out.println("Cyclic");
System.exit(-1);
}
root.visited = true;
// populate stack
if (!(root.val == null) && !stack.contains(root.val)) stack.push(root.val);
// traverse nodes
if (!root.adj.isEmpty()) {
for (Node<T> node : root.adj) {
dfs(stack, node);
}
}
root.visited = false;
}
}
public static void main(String[] args) {
System.out.println("HelloWord");
DAG<Character> dag = new DAG<Character>();
dag.add('a', 'b');
dag.add('b', 'c');
dag.add('z');
dag.add('c', 'd');
dag.add('d', 'e');
dag.add('d', 'z');
dag.add('z', 'd');
dag.add('z', 'a');
//dag.add('b','a');
System.out.println(dag.map.size());
System.out.println(dag.print());
System.out.println(dag.map.size());
}
}
output:
6
6
I re-did the dfs and print methods to this:
new DFS:
if root visited then cycle exists
if stack contains root val then branch has been traversed. just return
mark root to visited
dfs adjacent nodes
push root val to stack
mark root unvisited
New print() // returns topsort I should change the name I know
make a result stack and string builder
loop through map.keySet
if key.val not in stack -> call dfs
pop stack to string builder
string
public String print() {
Stack<T> stack = new Stack<>();
StringBuilder res = new StringBuilder();
for(T val: map.keySet()){
if (!stack.contains(val)) dfs(stack,map.get(val));
}
while(!stack.isEmpty()) res.append(stack.pop());
return res.toString();
}
public void dfs(Stack<T> stack, Node<T> root) {
if (root.visited) {
System.out.println("Cycle at :" + root.val.toString());
System.exit(-1);
}
if (stack.contains(root.val)) return;
root.visited = true;
for (Node<T> n: root.adj) dfs(stack,n);
stack.add(root.val);
root.visited =false;
}

Java Level order to N-Ary tree (Iterative and not recursion)

trying to convert a level order input to a N-Ary tree. Where levels are separated by a null. Example.
Input: [1, null, 2,3,4, null,5,6,null,7,8,null,9,10]
Code is expected to build a tree and finally print the preorder of the same for validation.
Output: [1,2,5,6, 3,7,8,4,9,10]
Not getting the desired output. Also this needs to be solved iteratively and recursion may not be used. Below is the full code. Added some print statement to ease debugging.
enter code here
package AllTree;
import java.util.*;
public class ListToNArrayTree {
public static class Node{
public int val;
public ArrayList<Node> children = new ArrayList<>();
public Node (int val){
this.val = val;
}
public Node (int val, ArrayList<Node> children){
this.val = val;
this.children = children;
}
public String toString(){
return " " + val;
}
public ArrayList<Node> getChildren() {
return children;
}
public void setChildren(ArrayList<Node> children) {
this.children = children;
}
}
public static Node buildTree(List<Integer> dataAsList){
/*Check if the input is valid to create a tree example {1, null, 2,3,4, null,5,6,null,7,8,null,9,10, null};
Above is a level order so null is mandatory # position 1.
*/
if (dataAsList.isEmpty() || dataAsList.get(0) == null|| dataAsList.get(1) !=null){
System.out.println ("Invalid data to construct a tree");
return null;
}
/*Create queue to hold all values from input*/
Queue<Integer> dataAsQueue = new LinkedList<>();
for (Integer data: dataAsList) {
dataAsQueue.add(data);
}
/*Create queue to hold the nodes which will be retrieved in FIFO to add corresponding children*/
Queue<Node> dataAsTree = new LinkedList<>();
Node root = new Node(dataAsQueue.poll()); // to poll the root element
dataAsQueue.poll(); // to poll the null - as after this is the beginning of the second level of the tree
dataAsTree.add(root);
root = dataAsTree.poll();
Node parent = root;
while (!dataAsQueue.isEmpty()) {
Node parent_ = parent;
Integer childInt= dataAsQueue.poll();
if (childInt != null){
parent_.getChildren().add(new Node(childInt));
dataAsTree.add(new Node(childInt));
}
else{
parent = dataAsTree.poll();
}
System.out.println ("Current parent " + parent_ + " with children" + parent_.children);
}
return root;
}
public static void main(String[] args){
List<Integer> dataAsList = Arrays.asList(1, null, 2,3,4, null,5,6,null,7,8,null,9,10);
// Node root = buildTree(dataAsList);
System.out.println ("PreOrder Sorting" + preorder( buildTree(dataAsList)));
}
public static List<Integer> preorder(Node root) {
LinkedList<Integer> res = new LinkedList<>();
if (root == null) {
return res;
}
preorderhelper(root, res);
return res;
}
private static void preorderhelper(Node root, LinkedList<Integer> res) {
if (root == null) {
return;
}
res.add(root.val);
if (root.children != null) {
for (Node c : root.children) {
preorderhelper(c, res);
}
}
}
}

Print all nodes that are N level above all Leaf Nodes

I need to print all the nodes that are N level above all Leaf Nodes. I tried below approach, but now I am stuck and unable to proceed. Please help. I need to code only using Java 7 and no other versions.
For example, I have this path 1 --> 2 --> 3 --> 4, so in this case assuming 4 is my leaf node, node 3 is 1 level above 4 and node 2 is 2 levels above leaf node 4 and node 1 is 3 levels above leaf node 4.
Note: Please use only Java 7.
public class NNodeBeforeLeaf {
static Node root;
static class Node {
int data;
Node left, right;
Node(int data){
this.data = data;
left=right=null;
}
}
public static boolean isLeaf(Node n){
if(n.right == null && n.left == null)
return true;
return false;
}
public static void main(String[] args) {
int level = 2; // level N
root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.left.left = new Node(4);
root.left.right = new Node(5);
root.right.left = new Node(8);
print(root, 0, level);
}
public static void print(Node n, int currLevel, int level){
if(n == null){
return;
}
if(!isLeaf(n)){
print(n.left, currLevel + 1, level);
print(n.right, currLevel + 1, level);
}
printNode(n, currLevel, level);
}
public static void printNode(Node n, int currLevel, int level){}
}
You have a miss in your structure to do this a Node know its child but not is parent so you need to build a structure that will give you this link : here is my proposition : i build a map that give me the parent associate to a node with method buildParentMap this function already list all the leaf in one pass to avoid a double iteration on your tree then i use this map to go up as many time as asked on each leaf i list just before here is a snippet
be carefull this code work but there is no security if your are trying to upper that root or if the same node is present in too child (but 2 Node with the same data wont be a problem)
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
public class NNodeBeforeLeaf {
static Node root;
static class Node {
int data;
Node left, right;
Node(int data) {
this.data = data;
left = right = null;
}
#Override
public String toString() {
return "Node : " + data;
}
}
public static boolean isLeaf(Node n) {
if (n.right == null && n.left == null)
return true;
return false;
}
public static void main(String[] args) {
int level = 2; // level N
root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.left.left = new Node(4);
root.left.right = new Node(5);
root.right.left = new Node(8);
print(root, 0, level);
int levelToUp = 1;
HashSet<Node> result = getUpper(levelToUp, root);
System.out.println(Arrays.toString(result.toArray()));
}
private static HashSet<Node> getUpper(int levelToUp, Node node) {
HashMap<Node, Node> parenttMap = new HashMap<Node, Node>();
LinkedList<Node> leafs = new LinkedList<Node>();
buildParentMap(node, parenttMap, leafs);
HashSet<Node> result = new HashSet<>();
for (Node leaf : leafs) {
result.add(getUpperLevel(leaf, levelToUp, parenttMap));
}
return result;
}
private static Node getUpperLevel(Node leaf, int i, HashMap<Node, Node> parenttMap) {
Node tmp = leaf;
while (i > 0) {
i--;
tmp = parenttMap.get(tmp);
}
return tmp;
}
private static void buildParentMap(Node root2, HashMap<Node, Node> hashMap, LinkedList<Node> leaf) {
if (root2 == null) {
return;
} else if (isLeaf(root2)) {
leaf.add(root2);
} else {
hashMap.put(root2.left, root2);
buildParentMap(root2.left, hashMap, leaf);
hashMap.put(root2.right, root2);
buildParentMap(root2.right, hashMap, leaf);
}
}
public static void print(Node n, int currLevel, int level) {
if (n == null) {
return;
}
printNode(n, currLevel, level);
if (!isLeaf(n)) {
print(n.left, currLevel + 1, level);
print(n.right, currLevel + 1, level);
}
}
public static void printNode(Node n, int currLevel, int level) {
String output = "";
for (int i = 0; i < currLevel; i++) {
output += "\t";
}
System.out.println(output + n);
}
}
PLEASE READ MY COMMENT FIRST
Since the nodes in your program store data only for the nodes below them, I couldn't really find a way of actually going up the tree ':), but I could think of this work around, basically what you can do is, each time you need to go up by n levels you can traverse down from the root to (curLevel - n) here is a sample program that does this (it prints all the nodes at a level which is n above the current level, i hope this is what you meant):
class tree{
static class Node{
int data;
Node left;
Node right;
Node(int data){
this.data = data;
left = null;
right = null;
}
}
static Node root;
public static boolean isLeaf(Node n){
if(n.left == null && n.right == null)
return true;
return false;
}
public static void goDownTillLevel(Node n, int level){
int l = level;
if(n != null){
if(level == 0) {
System.out.println(n.data);
}
else{
if(!isLeaf(n)){
goDownTillLevel(n.left, --level);
level = l; //since by the time the above function calls finished, level had been reduced to 0
goDownTillLevel(n.right, --level);
}
}
}
}
public static void nLevelsAbove(Node n, int curLevel, int level){
goDownTillLevel(root, (curLevel - level - 1));
}
public static void main(String args[]){
int curLevel = 0;
root = new Node(1);
curLevel++;
root.left = new Node(2);
root.right = new Node(2);
curLevel++;
root.left.left = new Node(3);
root.left.right = new Node(3);
root.right.left = new Node(3);
Node n = new Node(3);
root.right.right = n;
curLevel++;
nLevelsAbove(n, curLevel, 1);
}
}
Though I'd like to add that if going up is one of your concerns, don't use this node structure, instead add another variable to the node, a reference to the node right above it, that way this could be made much easier and shorter.
The output of the above code is:
2
2
I think that the implementation of public static boolean isLeaf(Node n) is wrong, it should check only if right is null otherwise it is not a node, either a leaf
To get the current level of node, you can try with this code
int level = 0;
while(node.right != null) {
level++;
node = node.right;
}
System.out.println("current level node: " + level);
Your structure is not able to determine the height of the current node, except when traversing from bottom to top. In order to achieve this, you have to traverse to the leafs first.
Each recursion (bottom up now) should then return it's heights. As youre not stating if your tree is a full binary tree, a node can have multiple heights depending on his children. If the heights match the desired height, the node can be printed.
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
public class NNodeBeforeLeaf {
static Node root;
static class Node {
int data;
Node left, right;
Node(int data) {
this.data = data;
left = right = null;
}
}
public static boolean isLeaf(Node n) {
return n.right == null && n.left == null;
}
public static void main(String[] args) {
int level = 2; // level N
root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.left.left = new Node(4);
root.left.right = new Node(5);
root.right.left = new Node(8);
print(root, level);
}
public static void print(Node n, int level) {
traversAndPrint(n, level);
}
private static Set<Integer> traversAndPrint(Node n, int levelToPrint) {
if (isLeaf(n)) return Collections.singleton(0); // We are a leaf, so we have height 0
final Set<Integer> childrenHeights = new HashSet<>();
// are no leaf, so we have to get the heights of our children
if (n.right != null) childrenHeights.addAll(traversAndPrint(n.right, levelToPrint));
if (n.left != null) childrenHeights.addAll(traversAndPrint(n.left, levelToPrint));
assert !childrenHeights.isEmpty();
// And increase these heights
final Set<Integer> selfHeights = new HashSet<>();
for (Integer childrenHeigth : childrenHeights) {
final int selfHeight = childrenHeigth + 1;
selfHeights.add(selfHeight);
}
// If we have the desired height, print
if (selfHeights.contains(levelToPrint)) printNode(n);
return selfHeights; // return our heights
}
public static void printNode(Node n) {
// Do whatever you want
System.out.println(n.data);
}
}
I found another approach. I put all nodes in a list. For each level up I remove the leaf nodes in that list. A leaf node in the list is defined as a node with left=null and right=null or if they are not null left and right should not be in the list. After the level ups I print the now leaf nodes in the list.
public class NNodeBeforeLeaf {
static Node root;
static class Node {
int data;
Node left, right;
Node(int data) {
this.data = data;
left = right = null;
}
}
public static boolean isLeaf(Node n) {
if ((n.right == null) && (n.left == null)) {
return true;
}
return false;
}
public static void main(String[] args) {
int level = 2; // level N
root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.left.left = new Node(4);
root.left.right = new Node(5);
root.right.left = new Node(8);
printNodes(getNodesNLevelAboveLeafs(root, level));
}
public static void printNodes(List<Node> nodes) {
for (Node n : nodes) {
System.out.println(n.data);
}
}
public static List<Node> getNodesNLevelAboveLeafs(Node root, int level) {
List<Node> allNodes = listAllNodes(root);
for (int i = 0; i < level; i++) {
allNodes.removeAll(getLeafNodes(allNodes));
}
return getLeafNodes(allNodes);
}
private static List<Node> getLeafNodes(List<Node> allNodes) {
List<Node> leafs = new ArrayList<>();
for (Node n : allNodes) {
if (((n.left == null) || !allNodes.contains(n.left))
&& ((n.right == null) || !allNodes.contains(n.right))) {
leafs.add(n);
}
}
return leafs;
}
private static List<Node> listAllNodes(Node node) {
List<Node> nodes = new ArrayList<>();
nodes.add(node);
if (node.left != null) {
nodes.addAll(listAllNodes(node.left));
}
if (node.right != null) {
nodes.addAll(listAllNodes(node.right));
}
return nodes;
}
}

Adding Node to Initially Null LinkedList

I'm having issues when I try to add a node to a linked list that is initialized to null. In my method I set a test case to check if the node is initially null and if so it creates a new node with the value that was passed in. But for whatever reason it doesn't work unless the node has atleast one element already passed in. Check it out:
Node addNode(Node node, int val)
{
if(node == null)
{
Node newNode = new Node(val);
//node = newNode;
return newNode;
}
node.next = addNode(node.next, val);
return node;
}
//Driver Class
Scanner in = new Scanner(System.in);
Node myNode = new Node(1);
int numEntries = in.nextInt();
for(int i = 0 ; i < numEntries ; i++)
{
int inputVal = in.nextInt();
myNode.addNode(myNode, inputVal);
}
The above code will not run if myNode is initialized to a null value (Node myNode = null;)
Full Code:
/* package whatever; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
public static class Node
{
private int value;
Node next;
public Node()
{
next = null;
}
public Node(int val)
{
value = val;
next = null;
}
Node addNode(Node node, int val)
{
if(node == null)
{
Node newNode = new Node(val);
//node = newNode;
return newNode;
}
node.next = addNode(node.next, val);
return node;
}
}
public static void main (String[] args) throws java.lang.Exception
{
Scanner in = new Scanner(System.in);
Node myNode = new Node(1);
Node current = null;
Node oddFirst = new Node(1);
int numEntries = in.nextInt();
for(int i = 0 ; i < numEntries ; i++)
{
int inputVal = in.nextInt();
myNode.addNode(myNode, inputVal);
}
current = myNode;
while(current != null) // Check if values were copied correctly
{
if(oddFirst == null)
{
oddFirst = new Node(current.value);
}
oddFirst.addNode(oddFirst,current.value);
//oddFirst = current.next;
//oddFirst = oddFirst.next;
current = current.next.next;
}
while(oddFirst != null)
{
System.out.println("Current Value: " + oddFirst.value);
oddFirst = oddFirst.next;
}
}
}
A simple solution for a linked list:
class Node {
int val;
Node next;
}
public class LinkedList {
public Node first;
public Node last;
public void addNext(int val) {
Node node = new Node();
node.val = val;
if(last == null) {
first = last = node;
}
else {
last.next = node;
last = node;
}
}
}
The main issue with the original code is that it doesn't concern itself with the case of the empty list.
You cannot discern the case where the list is comprised of a single 1 value, and the empty list.
Because you're not handling the return value of addNode().
You're returning a Node in the following function:
Node addNode(Node node, int val)
but you're not handling the return here:
myNode.addNode(myNode, inputVal);
This should help you figure out the solution.

how to merge 2 linked lists

I am trying to make a method to merge two linked lists for a homework assignment in my programming class. I'm really confused here, the method has to have this method signature:
public UnorderedLinkedListInt merge2(UnorderedLinkedListInt list), so in my tester method it will look like this list3 = list1.merge2(list2). I'm confused on how to make this when the method only takes in one list and not both. Here is my code so far
public class UnorderedLinkedListInt extends LinkedListIntClass {
//Default constructor
public UnorderedLinkedListInt() {
super();
}
public boolean search(int searchItem) {
LinkedListNode current; //variable to traverse the list
current = first;
while (current != null)
if (current.info == searchItem)
return true;
else
current = current.link;
return false;
}
public void insertFirst(int newItem) {
LinkedListNode newNode; //variable to create the new node
//create and insert newNode before first
newNode = new LinkedListNode(newItem, first);
first = newNode;
if (last == null)
last = newNode;
count++;
}
public void insertLast(int newItem) {
LinkedListNode newNode; //variable to create the new node
//create newNode
newNode = new LinkedListNode(newItem, null);
if (first == null) {
first = newNode;
last = newNode;
}
else {
last.link = newNode;
last = newNode;
}
count++;
}
public void deleteNode(int deleteItem) {
LinkedListNode current; //variable to traverse the list
LinkedListNode trailCurrent; //variable just before current
boolean found;
//Case 1; the list is empty
if ( first == null)
System.err.println("Cannot delete from an empty list.");
else {
//Case 2: the node to be deleted is first
if (first.info == deleteItem) {
first = first.link;
if (first == null) //the list had only one node
last = null;
count--;
}
else { //search the list for the given info
found = false;
trailCurrent = first; //trailCurrent points to first node
current = first.link; //current points to second node
while (current != null && !found) {
if (current.info == deleteItem)
found = true;
else {
trailCurrent = current;
current = current.link;
}
}
//Case 3; if found, delete the node
if (found) {
count--;
trailCurrent.link = current.link;
if (last == current) //node to be deleted was the last node
last = trailCurrent;
}
else
System.out.println("Item to be deleted is not in the list.");
}
}
}
public void merge(UnorderedLinkedListInt list2){
UnorderedLinkedListInt list1 = this;
while (list2.first != null) {//while more data to print
list1.insertLast(list2.first.info);
list2.first = list2.first.link;
}
}
public UnorderedLinkedListInt merge2(UnorderedLinkedListInt list2){
UnorderedLinkedListInt list3 = new UnorderedLinkedListInt();
UnorderedLinkedListInt list1 = this;
while (list1.first != null) {//while more data to print
list3.insertLast(list1.first.info);
list1.first = list1.first.link;
}
while (list2.first != null) {//while more data to print
list3.insertLast(list2.first.info);
list2.first = list2.first.link;
}
return list3;
}
}
I'm still having some trouble understanding exactly how linked lists work, any suggestions as to how to design this method would be greatly appreciated.
In a method call like list1.merge2(list2), the method receives list1 as the implicit "current object" that you can access with the this reference.
If you want to you can use another name for it:
public UnorderedLinkedListInt merge2(UnorderedLinkedListInt list2){
UnorderedLinkedListInt list1 = this;
// now merge list1 and list2
}
Your first list would be actual Object pointed to by the this reference.
Try this:
import java.io.*;
class Node1
{
int data;
Node1 link;
public Node1()
{
data=0;
link=null;
}
Node1 ptr,start,temp,ptr1;
void create()throws IOException
{
int n;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter first data");
this.data=Integer.parseInt(br.readLine());
ptr=this;
start=ptr;
char ins ='y';
do
{
System.out.println("Wanna Insert another node???");
ins=(char)br.read();
br.read();
if(ins=='y')
{
temp=new Node1();
System.out.println("Enter next data");
temp.data=Integer.parseInt(br.readLine());
temp.link=null;
ptr.link=temp;
temp=null;
ptr=ptr.link;
}
}while(ins=='y');
}
void merge()throws IOException
{
ptr1=this;
ptr=this;
Node1 t=new Node1();
t.create();
while(ptr1.link!=null)
{ ptr1=ptr1.link;}
ptr1.link=t.start;
ptr1=t=null;
System.out.println("---------------------------");
System.out.println("Merged LL :\n");
while(ptr!=null)
{
System.out.print("-->"+ptr.data);
ptr=ptr.link;
}
}
}

Categories