i've got some troubles with the Binary Tree Sort in Java.
I need to create the following method, but i don't get it, how to implement the position (pos) properly.
The excercise is to implement the Binary Tree Sort with the given signature. We then should initialize an int[] which size has to be at least the size of the Nodes in the tree.
The method
int binSort(Node node, int[] a, int pos){...}
should place the values of each node/leaf into the array a, at position pos.
I am not allowed to use global variables!
And as you can see, we need to implement the inOrder traversal
public class BinaryTree {
Node root;
int elements;
public BinaryTree() {
this.elements = 0;
}
public void addNode(int key, String name) {
Node newNode = new Node(key, name);
if (root == null) {
root = newNode;
} else {
Node focusNode = root;
Node parent;
while (true) {
parent = focusNode;
if (key < focusNode.getPriority()) {
focusNode = focusNode.getLeftChild();
if (focusNode == null) {
parent.setLeftChild(newNode);
return;
}
} else {
focusNode = focusNode.getRightChild();
if (focusNode == null) {
parent.setRightChild(newNode);
return;
}
}
}
}
}
public int binSort(Node focusNode, int[] a, int pos) {
int tmp = pos++;
if (focusNode != null) {
if (focusNode.getLeftChild() != null) {
binSort(focusNode.getLeftChild(), a, tmp);
}
System.out.println(focusNode.toString() + " - " + tmp++);
if (focusNode.getRightChild() != null) {
binSort(focusNode.getRightChild(), a, tmp);
}
return focusNode.getPriority();
}
return -1;
}
public static void main(String[] args) {
BinaryTree tree = new BinaryTree();
tree.addNode(50, "Boss");
tree.addNode(30, "Boss");
tree.addNode(10, "Boss");
tree.addNode(70, "Boss");
tree.addNode(9, "Boss");
tree.addNode(15, "Boss");
tree.addNode(78, "Boss");
tree.addNode(36, "Boss");
int[] a = new int[8];
tree.binSort(tree.root, a, 0);
System.out.println(tree.root.getPriority());
System.out.println("");
System.out.println(Arrays.toString(a));
}
}
My Output:
Boss has a key 9 - 0
Boss has a key 10 - 0
Boss has a key 15 - 1
Boss has a key 30 - 0
Boss has a key 36 - 1
Boss has a key 50 - 0
Boss has a key 70 - 1
Boss has a key 78 - 2
just ignore "Boss" (it is just a useless value at the moment!)
the important part is that the specific values which should be placed into the array are perfectly ordered (9,10,15,30,..,78), but the positions are not! (0,0,1,0,1,0,1,2)
I have no idea how to fix this.
Btw. the class "Node":
String val;
int priority;
Node leftChild;
Node rightChild;
public Node(int priority, String val) {
this.priority = priority;
this.val = val;
}
public int getPriority() {
return this.priority;
}
public String getVal() {
return this.val;
}
public Node getLeftChild() {
return leftChild;
}
public Node getRightChild() {
return rightChild;
}
public void setLeftChild(Node child) {
this.leftChild = child;
}
public void setRightChild(Node child) {
this.rightChild = child;
}
public String toString() {
return val + " has a key " + priority;
}
I hope that your are able to help me solving this problem.
ok, i found the solution on my own :)
public int binSort(BinTreeNode nnode, int[] a, int pos) {
if (nnode != null) {
if (nnode.getLeftChild() != null) {
pos = binSort(nnode.getLeftChild(), a, pos);
}
a[pos] = nnode.getValue();
pos++;
if (nnode.getRightChild() != null) {
pos = binSort(nnode.getRightChild(), a, pos);
}
return pos;
}
return -1;
}
I needed to return pos, instead of focusNode.getPriority() and I only have to increment pos by 1, after I added the value of the current node!
Related
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.
The point of this project is to get an array from the user and use it to create a tree using nodes. The next step is to call a method to check if it represents a Binary Tree. I've been working on this for hours and can't seem to find the correct method to check.
Here is my code so far. I have done everything but the isBinaryTree() method to check if it is a Binary Tree.
import java.util.Scanner;
public class TestBinaryTree
{
Node root;
public void addNode(int key)
{
Node newNode = new Node(key);
if(root == null)
{
root = newNode;
}
else
{
Node focusNode = root;
Node parent;
while(true)
{
parent = focusNode;
if(key < focusNode.key)
{
focusNode = focusNode.leftChild;
if(focusNode == null)
{
parent.leftChild = newNode;
return;
}
}
else
{
focusNode = focusNode.rightChild;
if(focusNode == null)
{
parent.rightChild = newNode;
return;
}
}
}
}
}
/*public static boolean isBinaryTree(int rt, int lft, int rght)
{
}*/
public static void main(String[] args)
{
int Nroot, Nleft, Nright;
Scanner input = new Scanner(System.in);
TestBinaryTree theTree = new TestBinaryTree();
System.out.println("How many numbers are in the array: ");
int num = input.nextInt();
int arr[]=new int[num];
System.out.println("Enter the numbers: ");
for(int i=0;i<num;i++)
{
arr[i] = input.nextInt();
theTree.addNode(arr[i]);
}
}
}
class Node
{
int key;
Node leftChild;
Node rightChild;
Node(int key)
{
this.key = key;
}
public String toString()
{
return "Node: " + key;
}
}
I am trying to write a method that returns the depth of a target int in a binary search tree. Right now it works for some smaller trees, but not always. Does anyone see where I may be going wrong?
static int count=1;
public static int findDepth(TreeNode<Integer> root, int target)
// pre: 0 or more elements in the tree, integer to search for
// post: return depth of target if found, -1 otherwise
{
count++;
if (root!=null)
{
if (root.getValue()<target)
{
if (root.getValue()==target)
{System.out.println(count);
return count;}
else
{findDepth(root.getLeft(), target);
count--;
findDepth(root.getRight(), target);
}
}
else if (root.getValue()>target)
{
if (root.getValue()==target)
{System.out.println(count);
return count;}
else
{findDepth(root.getLeft(), target);
count--;
findDepth(root.getRight(), target);
}
}
else if (root.getValue()==target)
return 1;
else
return -1;
}
return count;
}
There's a few things wrong.
It will never get into this case:
if (root.getValue()<target)
{
if (root.getValue()==target)
{System.out.println(count);
return count;}
Also it will never get into this case:
else if (root.getValue()>target)
{
if (root.getValue()==target)
{System.out.println(count);
return count;}
The biggest issue is that you're keeping a global static count, and recursively going through both left and right paths.
First of all, for a BST, there is no need to go both left and right.
Second, it's better to pass the count through a parameter rather than keeping a global.
Rather than fix your code, I'll post this working example for you to use as a reference:
public class Main
{
public static void main(String[] args)
{
BinaryTree tree = new BinaryTree();
tree.add(20);
tree.add(10);
tree.add(30);
tree.add(15);
tree.add(25);
tree.add(5);
tree.add(35);
tree.add(1);
tree.add(6);
tree.add(14);
tree.add(16);
tree.add(24);
tree.add(26);
tree.add(34);
tree.add(36);
int level = tree.getLevel(6);
System.out.println(level);
}
}
public class TreeNode
{
int data;
TreeNode left;
TreeNode right;
public TreeNode(int d){
data = d;
left = null;
right = null;
}
}
public class BinaryTree
{
TreeNode root;
public BinaryTree(){
root = null;
}
public int getLevel(int val) {
if (root == null) return 0;
return getLevelHelper(root, val, 0);
}
public int getLevelHelper(TreeNode node, int val, int level){
int retVal = -1;
if (node.data == val){
return level;
}
if (val < node.data && node.left != null){
retVal = getLevelHelper(node.left, val, level + 1);
}
else if (val > node.data && node.right != null){
retVal = getLevelHelper(node.right, val, level + 1);
}
return retVal;
}
public boolean add(int newData){
if (root == null){
root = new TreeNode(newData);
return true;
}
else{
TreeNode curr = root;
while (true){
if (curr.data == newData){
return false;
}
else if (curr.data > newData){
if (curr.left == null){
curr.left = new TreeNode(newData);
return true;
}
else{
curr = curr.left;
}
}
else{
if (curr.right == null){
curr.right = new TreeNode(newData);
return true;
}
else{
curr = curr.right;
}
}
}
}
}
}
I have to complete the method maxElem(Node node) in such a way that the method maxElem() returns the maximum value contained in a binary tree.
How can I do that? I do not know how to do that..
public class BinaryTree {
protected class Node {
protected Integer element;
protected Node left;
protected Node right;
Node(int element) {
this.element = element;
left = right = null;
}
Node(int element, Node left, Node right) {
this.element = element;
this.left = left;
this.right = right;
}
} //end Node class
public class NodeReference {
private Node node;
private NodeReference(Node node) {
this.node = node;
}
public int getElement() {
return node.element;
}
public void setElement(int e) {
node.element = e;
}
}
protected Node root;
public BinaryTree() {
root = null;
}
private class BoolNode {
boolean found;
Node node;
BoolNode(boolean found, Node node) {
this.found = found;
this.node = node;
}
}
public int maxElem() {
if(root == null)
throw new IllegalStateException("Empty tree.");
return maxElem(root);
}
private static int max3(int x, int y, int z) {
return max(x, max(y, z));
}
private int maxElem(Node node) {
//...
}
}
Thanks a lot!
Try:
private int maxElem(Node node) {
int max = node.element;
if(node.left != null) {
max = Math.max(max, maxElem(node.left));
}
if(node.right != null) {
max = Math.max(max, maxElem(node.right));
}
return max;
}
1)Using Recursion:
Note:You need the add getElement(), getRight(), getLeft() methods in your Node class so that the below code could work.
public int findMaxInTree(Node root) {
int max = Integer.MIN_VALUE; //set a default max value
if (root == null)
return max; //if root is null
else {
int left_max = findMaxInTree(root.getLeft()); //get left side max
int right_max = findMaxInTree(root.getRight()); //get right side max
if (left_max > right_max) //if left>right
max = left_max; //set max=left
else
max=right_max; //else set max=right
if (root.getElement() > max) //if root is greater than max of left or right
max = root.getElement(); //set max=root
}
return max; //return max
}
2)You can use the concept of Breadth First Traversal to find the max.
public void findMax(Node root) {
if (root == null)
System.out.println("empty tree");
else {
Queue<Node> queue = new LinkedList<Node>(); //make a queue
Node max = root; //suppose max is root
queue.add(root); //add root to queue
while (queue.size() != 0) { //while size of queue is not empty
Node temp = queue.remove(); //remove an item from queue
if (temp.getElement() > max.getElement()) //if removed item is greater than max
max = temp; //set new max
if (temp.getLeft() != null)
queue.add(temp.getLeft()); //traverse left
if (temp.getRight() != null)
queue.add(temp.getRight()); //traverse right
}
System.out.println(max.getElement()); //in the end ,print the max
}
}
Here is one way you could get the maximum value of a tree.
public static int maxElem(Node node) {
if (node == null) {
return Integer.MIN_VALUE;
}
int max = Math.max(maxElem(node.left), maxElem(node.right));
return max > node.element ? max : node.element;
}
public static void maxElement(Node node, int max){
static int MaxTemp;
if(node==null)
return;
if(node.getData()>min)
MaxTemp=node.getData();
if(node.getLeft()!=null && node.getLeft().getData()>max)
MaxTemp=node.getLeft().getData();
if(node.getRight()!=null && node.getRight().getData()>max)
MaxTemp=node.getRight().getData();
maxElement(node.getLeft(), MaxTemp);
maxElement(node.getRight(), MaxTemp);
}
public static int maxInTree(BinTreeNode<int> t)
{
int max = t.GetInfo();
if (t != null)
{
if (t.GetLeft() != null)
max = Math.Max(max, maxInTree(t.GetLeft()));
if (t.GetRight() != null)
max = Math.Max(max, maxInTree(t.GetRight()));
}
return max;
}
I'm practicing basic data structure stuff and I'm having some difficulties with recursion. I understand how to do this through iteration but all of my attempts to return the nth node from the last of a linked list via recursion result in null. This is my code so far:
public static int i = 0;
public static Link.Node findnthToLastRecursion(Link.Node node, int pos) {
if(node == null) return null;
else{
findnthToLastRecursion(node.next(), pos);
if(++i == pos) return node;
return null;
}
Can anyone help me understand where I'm going wrong here?
This is my iterative solution which works fine, but I'd really like to know how to translate this into recursion:
public static Link.Node findnthToLast(Link.Node head, int n) {
if (n < 1 || head == null) {
return null;
}
Link.Node pntr1 = head, pntr2 = head;
for (int i = 0; i < n - 1; i++) {
if (pntr2 == null) {
return null;
} else {
pntr2 = pntr2.next();
}
}
while (pntr2.next() != null) {
pntr1 = pntr1.next();
pntr2 = pntr2.next();
}
return pntr1;
}
You need to go to the end and then count your way back, make sure to pass back the node each time its passed back. I like one return point
public static int i = 0;
public static Link.Node findnthToLastRecursion(Link.Node node, int pos) {
Link.Node result = node;
if(node != null) {
result = findnthToLastRecursion(node.next, pos);
if(i++ == pos){
result = node;
}
}
return result;
}
Working example outputs 7 as 2 away from the 9th and last node:
public class NodeTest {
private static class Node<E> {
E item;
Node<E> next;
Node<E> prev;
Node(Node<E> prev, E element, Node<E> next) {
this.item = element;
this.next = next;
this.prev = prev;
}
}
/**
* #param args
*/
public static void main(String[] args) {
Node first = null;
Node prev = null;
for (int i = 0; i < 10; i++) {
Node current = new Node(prev, Integer.toString(i),null);
if(i==0){
first = current;
}
if(prev != null){
prev.next = current;
}
prev = current;
}
System.out.println( findnthToLastRecursion(first,2).item);
}
public static int i = 0;
public static Node findnthToLastRecursion(Node node, int pos) {
Node result = node;
if (node != null) {
result = findnthToLastRecursion(node.next, pos);
if (i++ == pos) {
result = node;
}
}
return result;
}
}
No need for static variables.
public class List {
private Node head = null;
// [...] Other methods
public Node findNthLastRecursive(int nth) {
if (nth <= 0) return null;
return this.findNthLastRecursive(this.head, nth, new int[] {0});
}
private Node findNthLastRecursive(Node p, int nth, int[] pos) {
if (p == null) {
return null;
}
Node n = findNthLastRecursive(p.next, nth, pos);
pos[0]++;
if (pos[0] == nth) {
n = p;
}
return n;
}
}
You can do this a couple of ways:
recurse through the list once to find the list length, then write a recursive method to return the kth element (a much easier problem).
use an auxiliary structure to hold the result plus the remaining length; this essentially replaces the two recursions of the first option with a single recursion:
static class State {
Link.Node result;
int trailingLength;
}
public static Link.Node findnthToLastRecursion(Link.Node node, int pos) {
if(node == null) return null;
State state = new State();
findnthToLastRecursion(node, pos, state);
return state.result;
}
private static void findnthToLastRecursion(Link.Node node, int pos, State state) {
if (node == null) {
state.trailingLength = 0;
} else {
findnthToLastRecursion(node.next(), state);
if (pos == state.trailingLength) {
state.result = node;
}
++state.trailingLength;
}
}
I misunderstood the question. Here is an answer based on your iterative solution:
public static Link.Node findnthToLast(Link.Node head, int n) {
return findnthToLastHelper(head, head, n);
}
private static Link.Node findnthToLastHelper(Link.Node head, Link.Node end, int n) {
if ( end == null ) {
return ( n > 0 ? null : head);
} elseif ( n > 0 ) {
return findnthToLastHelper(head, end.next(), n-1);
} else {
return findnthToLastHelper(head.next(), end.next(), 0);
}
}
actually you don't need to have public static int i = 0; . for utill method the pos is :
pos = linked list length - pos from last + 1
public static Node findnthToLastRecursion(Node node, int pos) {
if(node ==null){ //if null then return null
return null;
}
int length = length(node);//find the length of the liked list
if(length < pos){
return null;
}
else{
return utill(node, length - pos + 1);
}
}
private static int length(Node n){//method which finds the length of the linked list
if(n==null){
return 0;
}
int count = 0;
while(n!=null){
count++;
n=n.next;
}
return count;
}
private static Node utill(Node node, int pos) {
if(node == null) {
return null;
}
if(pos ==1){
return node;
}
else{
return utill(node.next, pos-1);
}
}
Here node.next is the next node. I am directly accessing the next node rather than calling the next() method. Hope it helps.
This cheats (slightly) but it looks good.
public class Test {
List<String> list = new ArrayList<> (Arrays.asList("Zero","One","Two","Three","Four","Five","Six","Seven","Eight","Nine","Ten"));
public static String findNthToLastUsingRecursionCheatingALittle(List<String> list, int n) {
int s = list.size();
return s > n
// Go deeper!
? findNthToLastUsingRecursionCheatingALittle(list.subList(1, list.size()), n)
// Found it.
: s == n ? list.get(0)
// Too far.
: null;
}
public void test() {
System.out.println(findNthToLastUsingRecursionCheating(list,3));
}
public static void main(String args[]) {
new Test().test();
}
}
It prints:
Eight
which I suppose is correct.
I have use List instead of some LinkedList variant because I do not want to reinvent anything.
int nthNode(struct Node* head, int n)
{
if (head == NULL)
return 0;
else {
int i;
i = nthNode(head->left, n) + 1;
printf("=%d,%d,%d\n", head->data,i,n);
if (i == n)
printf("%d\n", head->data);
}
}
public class NthElementFromLast {
public static void main(String[] args) {
List<String> list = new LinkedList<>();
Stream.of("A","B","C","D","E").forEach(s -> list.add(s));
System.out.println(list);
System.out.println(getNthElementFromLast(list,2));
}
private static String getNthElementFromLast(List list, int positionFromLast) {
String current = (String) list.get(0);
int index = positionFromLast;
ListIterator<String> listIterator = list.listIterator();
while(positionFromLast>0 && listIterator.hasNext()){
positionFromLast--;
current = listIterator.next();
}
if(positionFromLast != 0) {
return null;
}
String nthFromLast = null;
ListIterator<String> stringListIterator = list.listIterator();
while(listIterator.hasNext()) {
current = listIterator.next();
nthFromLast = stringListIterator.next();
}
return nthFromLast;
}
}
This will find Nth element from last.
My approach is simple and straight,you can change the array size depending upon your requirement:
int pos_from_tail(node *k,int n)
{ static int count=0,a[100];
if(!k) return -1;
else
pos_from_tail(k->next,n);
a[count++]=k->data;
return a[n];
}
You'll have make slight changes in the code:
public static int i = 0;
public static Link.Node findnthToLastRecursion(Link.Node node, int pos) {
if(node == null) return null;
else{
**Link.Node temp = findnthToLastRecursion(node.next(), pos);
if(temp!=null)
return temp;**
if(++i == pos) return node;
return null;
}
}