Recursively find nth to last element in linked list - java

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

Related

Sorting sets of 4 ints in circular list

I am playing around with circular linked list to represent polynomials with it.
Here is what I have so far:
Class for parts of polynomial:
public class Wielomian {
int wsp;
int a;
int b;
int c;
public Wielomian(){
wsp=0;
a=-1;
b=-1;
c=-1;
}
public Wielomian(int wsp, int a, int b, int c){
this.wsp = wsp;
this.a = a;
this.b = b;
this.c = c;
}
public String toString(){
return wsp+"(x^"+a+")(y^"+b+")(z^"+c+")";
}
}
wsp is coefficient and a,b,c are exponents of x, y and z.
Node:
public class Node {
protected Object data;
protected Node link;
public Node() {
link = null;
data = 0;
}
public Node(Object d,Node n) {
data = d;
link = n;
}
public void setLink(Node n) {
link = n;
}
public void setData(Object d) {
data = d;
}
public Node getLink() {
return link;
}
public Object getData() {
return data;
}
}
List:
class linkedList {
protected Node start ;
protected Node end ;
public int size ;
public linkedList() {
start = null;
end = null;
size = 0;
}
public boolean isEmpty() {
return start == null;
}
public int getSize() {
return size;
}
public void insertAtStart(Object val) {
Node nptr = new Node(val,null);
nptr.setLink(start);
if(start == null) {
start = nptr;
nptr.setLink(start);
end = start;
}
else {
end.setLink(nptr);
start = nptr;
}
size++ ;
}
/* Function to insert element at end */
public void insertAtEnd(Object val) {
Node nptr = new Node(val,null);
nptr.setLink(start);
if(start == null) {
start = nptr;
nptr.setLink(start);
end = start;
}
else {
end.setLink(nptr);
end = nptr;
}
size++ ;
}
/* Function to insert element at position */
public void insertAtPos(Object val , int pos) {
Node nptr = new Node(val,null);
Node ptr = start;
pos = pos - 1 ;
for (int i = 1; i < size - 1; i++)
{
if (i == pos)
{
Node tmp = ptr.getLink() ;
ptr.setLink( nptr );
nptr.setLink(tmp);
break;
}
ptr = ptr.getLink();
}
size++ ;
}
/* Function to delete element at position */
public void deleteAtPos(int pos) {
if (size == 1 && pos == 1) {
start = null;
end = null;
size = 0;
return ;
}
if (pos == 1) {
start = start.getLink();
end.setLink(start);
size--;
return ;
}
if (pos == size) {
Node s = start;
Node t = start;
while (s != end) {
t = s;
s = s.getLink();
}
end = t;
end.setLink(start);
size --;
return;
}
Node ptr = start;
pos = pos - 1 ;
for (int i = 1; i < size - 1; i++) {
if (i == pos) {
Node tmp = ptr.getLink();
tmp = tmp.getLink();
ptr.setLink(tmp);
break;
}
ptr = ptr.getLink();
}
size-- ;
}
}
And I realised I need another add method that will and sort those parts of polynomial while adding - first by exponent of x, if 2 will have equal then by exponent of y and so on.
The elements of list will be parts of polynomial and there also will be "head" which will be linked to the part with highest exponent at "x" and the last part of polynomial will be linked to this "head" making whole list circular. Head will have coefficient that equals 0 and exponats that equal -1 each. But I have no idea how to implement such method without ruining all the links etc. etc. I hope You guys can help me :)
I would also like to know best way to display my polynomial later. Will it be some kind of iteration through parts of polynomial and adding them to String until i reach "head"?

Deleting a node at a given index in Java; What am I doing wrong?

I have been stuck for the last 40-so minutes on this problem. I'm unsure of what I am doing wrong here, I have tried debugging many times and have read similar Q/A's. Can't figure it out and my assignment is due at midnight.
It is not deleting the Node.. None at all in fact. If the code seems right, then the problem may be lying inside main. Let me know, please & thank you!
Any help is well appreciated! :)
Problem Method Below
void deleteAtIndex(int idx)
{
if (length() >= idx)
{
if(idx == 0)
{
head = head.getNext();
}
else
{
Node temp = findAtIndex(idx-1);
temp.setNext(temp.getNext().getNext());
}
}
else
System.out.println("Invalid position");
}
Full Class Code Below
public class ShapeLinkedList {
public Node head; // Head is first node in linked list
public ShapeLinkedList() { }
public ShapeLinkedList(Node head) {
}
public boolean isEmpty() {
return length() == 0;
}
public void insertAtEnd(Shape data) {
Node end = new Node(data, null);
if (head == null)
head.setNext(end);
else
tail().setNext(end);
}
public void insertAtBeginning(Shape data) {
if (data != null)
{
Node temp = new Node(data, head);
head = temp;
}
}
public Node tail() {
if (head == null){
return null;
}
else
{
Node temp = head;
while(temp.getNext() != null){
temp = temp.getNext();
}
return temp;
}
}
public int length() { // 1
Node temp = head;
if (temp == null)
return 0;
int tempIndex = 0;
while(temp.getNext() != null){
temp = temp.getNext();
tempIndex++;
}
return tempIndex;
}
void insertAtIndex(int idx, Shape data) { //3
if (length() >= idx)
{
Node current = new Node(data, null);
Node temp = findAtIndex(idx);
current.setNext(temp.getNext());
temp.setNext(current);
}
}
Node findAtIndex(int idx) { // 2
if (length() >= idx)
{
Node temp = head;
for(int i = 0; i < idx; i++)
{
temp = temp.getNext();
}
return temp;
}
else
return null;
}
void deleteAtIndex(int idx) { //4
if (length() >= idx)
{
if(idx == 0)
{
head = head.getNext();
}
else
{
Node temp = findAtIndex(idx-1);
temp.setNext(temp.getNext().getNext());
}
}
else
System.out.println("Invalid position");
}
#Override
public String toString() {
return "";
}
void deleteData(Shape s) {
Node temp = head;
for(int i = 0; i < length(); i++)
{
if(temp.getData() == s)
deleteAtIndex(i);
}
}
#Override
public int hashCode() {
return 0;
}
#Override
public boolean equals(Object obj) {
return false;
}
// Node is nested class because it only exists along with linked list
public static class Node {
private Shape data;
private Node next;
public Node(Shape S, Node N){
data = S;
next = N;
}
public Node getNext(){
return next;
}
public Shape getData() { return data; }
public void setNext(Node N) { next = N; }
// TODO develop all the methods that are needed
// such as constructors, setters, getters
// toString, equals, hashCode
}
}
You have multiple bugs in your class. I guess if you fix them, your code will work fine. SO is not a debugging platform, thus your question is off-topic and you should learn using a debugger.
Here some issues I instantly have seen from a quick look at your code, I'm sure there are more issues:
if (length() >= idx) should probably be if (length() > idx) at all places and
if (head == null) head.setNext(end); should probably be if (head == null) head = end; and
public ShapeLinkedList(Node head) { } should probably be public ShapeLinkedList(Node head) { this.head = head; } and
int tempIndex = 0 should probably be int tempIndex = 1

Finding a node in a binary search tree in java?

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

Linked List Array

I have this school assignment that I'm a little confused about.
Here's what it's saying:
"Write a program that uses the technique of 'chaining' for hashing.
The program will read in the length of an array which will contain the reference to each
linked list that will be generated. Furthermore, all values that are to be stored, is read.
The program shall have a separate function for hashing where the index exists. When the program have generated the linked lists, the theoretical 'load factor' is to be calculated and printed out. The whole array should be easily printed out."
The thing that I'm confused about, is the part about the program will read in the length of an array which will contain the reference to each linked list that will be generated. Is it possible to generate multiple linked lists? In that case, how do you do that?
This is the classes I'm told to use:
public class EnkelLenke {
private Node head = null;
private int numOfElements = 0;
public int getNum()
{
return numOfElements;
}
public Node getHead()
{
return head;
}
public void insertInFront(double value)
{
head = new Node (value, head);
++numOfElements;
}
public void insertInBack(double value)
{
if (head != null)
{
Node this = head;
while (this.next != null)
this = this.next;
this.next = new Node(value, null);
}
else
head = new Node(value, null);
++numOfElements;
}
public Node remove(Node n)
{
Node last = null;
Node this = head;
while (this != null && this != n)
{
last = this;
this = this.next;
}
if (this != null)
{
if (last != null)
last.next = this.next;
else
head = this.next;
this.next = null;
--numOfElements;
return this;
}
else
return null;
}
public Node findNr(int nr)
{
Node this = head;
if (nr < numOfElements)
{
for (int i = 0; i < nr; i++)
this = this.next;
return this;
}
else
return null;
}
public void deleteAll()
{
head = null;
numOfElements = 0;
}
public String printAllElements() {
String streng = new String();
Node this = head;
int i = 1;
while(this != null)
{
streng = streng + this.element + " ";
this = this.findNext();
i++;
if(i > 5)
{
i = 1;
streng = streng + "\n";
}
}
return streng;
}
public double getValueWithGivenNode (Node n)
{
Node this = head;
while (this != null && this != n)
{
this = this.next;
}
if (this == n)
return this.element;
else
return (Double) null;
}
}
public class Node {
double element;
Node next;
public Node(double e, Node n)
{
element = e;
next = n;
}
public double findElement()
{
return element;
}
public Node findNext()
{
return next;
}
}
Your data structure will look something like this (where "LL" is a linked list):
i | a[i]
-------------------------------
0 | LL[obj1 -> obj5 -> obj3]
1 | LL[obj2]
2 | LL[]
... | ...
N-1 | LL[obj4 -> obj6]
At each array index, you have a linked list of objects which hash to that index.
Is it possible to generate multiple linked lists? In that case, how do you do that?
Yes. Create your array, and initialize each element to a new linked list.
EnkelLenke[] a = new EnkelLenke[N];
for ( int i = 0; i < N; i++ ) {
a[i] = new EnkelLenke();
}

Binary Heap Implemented via a Binary Tree Structure

For an assignment, we were instructed to create a priority queue implemented via a binary heap, without using any built-in classes, and I have done so successfully by using an array to store the queued objects. However, I'm interested in learning how to implement another queue by using an actual tree structure, but in doing so I've run across a bit of a problem.
How would I keep track of the nodes on which I would perform insertion and deletion? I have tried using a linked list, which appends each node as it is inserted - new children are added starting from the first list node, and deleted from the opposite end. However, this falls apart when elements are rearranged in the tree, as children are added at the wrong position.
Edit: Perhaps I should clarify - I'm not sure how I would be able to find the last occupied and first unoccupied leaves. For example, I would always be able to tell the last inserted leaf, but if I were to delete it, how would I know which leaf to delete when I next remove the item? The same goes for inserting - how would I know which leaf to jump to next after the current leaf has both children accounted for?
A tree implementation of a binary heap uses a complete tree [or almost full tree: every level is full, except the deepest one].
You always 'know' which is the last occupied leaf - where you delete from [and modifying it is O(logn) after it changed so it is not a problem], and you always 'know' which is the first non-occupied leaf, in which you add elements to [and again, modifying it is also O(logn) after it changed].
The algorithm idea is simple:
insert: insert element to the first non-occupied leaf, and use heapify [sift up] to get this element to its correct place in the heap.
delete_min: replace the first element with the last occupied leaf, and remove the last occupied leaf. then, heapify [sift down] the heap.
EDIT: note that delete() can be done to any element, and not only the head, however - finding the element you want to replace with the last leaf will be O(n), which will make this op expensive. for this reason, the delete() method [besides the head], is usually not a part of the heap data structure.
I really wanted to do this for almost a decade.Finally sat down today and wrote it.Anyone who wants it can use it.I got inspired by Quora founder to relearn Heap.Apparently he was asked how would you find K near points in a set of n points in his Google phone screen.Apparently his answer was to use a Max Heap and to store K values and remove the maximum element after the size of the heap exceeds K.The approach is pretty simple and the worst case is nlog K which is better than n^2 in most sorting cases.Here is the code.
import java.util.ArrayList;
import java.util.List;
/**
* #author Harish R
*/
public class HeapPractise<T extends Comparable<T>> {
private List<T> heapList;
public List<T> getHeapList() {
return heapList;
}
public void setHeapList(List<T> heapList) {
this.heapList = heapList;
}
private int heapSize;
public HeapPractise() {
this.heapList = new ArrayList<>();
this.heapSize = heapList.size();
}
public void insert(T item) {
if (heapList.size() == 0) {
heapList.add(item);
} else {
siftUp(item);
}
}
public void siftUp(T item) {
heapList.add(item);
heapSize = heapList.size();
int currentIndex = heapSize - 1;
while (currentIndex > 0) {
int parentIndex = (int) Math.floor((currentIndex - 1) / 2);
T parentItem = heapList.get(parentIndex);
if (parentItem != null) {
if (item.compareTo(parentItem) > 0) {
heapList.set(parentIndex, item);
heapList.set(currentIndex, parentItem);
currentIndex = parentIndex;
continue;
}
}
break;
}
}
public T delete() {
if (heapList.size() == 0) {
return null;
}
if (heapList.size() == 1) {
T item = heapList.get(0);
heapList.remove(0);
return item;
}
return siftDown();
}
public T siftDown() {
T item = heapList.get(0);
T lastItem = heapList.get(heapList.size() - 1);
heapList.remove(heapList.size() - 1);
heapList.set(0, lastItem);
heapSize = heapList.size();
int currentIndex = 0;
while (currentIndex < heapSize) {
int leftIndex = (2 * currentIndex) + 1;
int rightIndex = (2 * currentIndex) + 2;
T leftItem = null;
T rightItem = null;
int currentLargestItemIndex = -1;
if (leftIndex <= heapSize - 1) {
leftItem = heapList.get(leftIndex);
}
if (rightIndex <= heapSize - 1) {
rightItem = heapList.get(rightIndex);
}
T currentLargestItem = null;
if (leftItem != null && rightItem != null) {
if (leftItem.compareTo(rightItem) >= 0) {
currentLargestItem = leftItem;
currentLargestItemIndex = leftIndex;
} else {
currentLargestItem = rightItem;
currentLargestItemIndex = rightIndex;
}
} else if (leftItem != null && rightItem == null) {
currentLargestItem = leftItem;
currentLargestItemIndex = leftIndex;
}
if (currentLargestItem != null) {
if (lastItem.compareTo(currentLargestItem) >= 0) {
break;
} else {
heapList.set(currentLargestItemIndex, lastItem);
heapList.set(currentIndex, currentLargestItem);
currentIndex = currentLargestItemIndex;
continue;
}
}
}
return item;
}
public static void main(String[] args) {
HeapPractise<Integer> heap = new HeapPractise<>();
for (int i = 0; i < 32; i++) {
heap.insert(i);
}
System.out.println(heap.getHeapList());
List<Node<Integer>> nodeArray = new ArrayList<>(heap.getHeapList()
.size());
for (int i = 0; i < heap.getHeapList().size(); i++) {
Integer heapElement = heap.getHeapList().get(i);
Node<Integer> node = new Node<Integer>(heapElement);
nodeArray.add(node);
}
for (int i = 0; i < nodeArray.size(); i++) {
int leftNodeIndex = (2 * i) + 1;
int rightNodeIndex = (2 * i) + 2;
Node<Integer> node = nodeArray.get(i);
if (leftNodeIndex <= heap.getHeapList().size() - 1) {
Node<Integer> leftNode = nodeArray.get(leftNodeIndex);
node.left = leftNode;
}
if (rightNodeIndex <= heap.getHeapList().size() - 1) {
Node<Integer> rightNode = nodeArray.get(rightNodeIndex);
node.right = rightNode;
}
}
BTreePrinter.printNode(nodeArray.get(0));
}
}
public class Node<T extends Comparable<?>> {
Node<T> left, right;
T data;
public Node(T data) {
this.data = data;
}
}
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
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) {
String nodeData = String.valueOf(node.data);
if (nodeData != null) {
if (nodeData.length() == 1) {
nodeData = "0" + nodeData;
}
}
System.out.print(nodeData);
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 < 2 * 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;
}
}
Please note that BTreePrinter is a code I took somewhere in Stackoverflow long back and I modified to use with 2 digit numbers.It will be broken if we move to 3 digit numbers and it is only for simple understanding of how the Heap structure looks.A fix for 3 digit numbers is to keep everything as multiple of 3.
Also due credits to Sesh Venugopal for wonderful tutorial on Youtube on Heap data structure
public class PriorityQ<K extends Comparable<K>> {
private class TreeNode<T extends Comparable<T>> {
T val;
TreeNode<T> left, right, parent;
public String toString() {
return this.val.toString();
}
TreeNode(T v) {
this.val = v;
left = null;
right = null;
}
public TreeNode<T> insert(T val, int position) {
TreeNode<T> parent = findNode(position/2);
TreeNode<T> node = new TreeNode<T>(val);
if(position % 2 == 0) {
parent.left = node;
} else {
parent.right = node;
}
node.parent = parent;
heapify(node);
return node;
}
private void heapify(TreeNode<T> node) {
while(node.parent != null && (node.parent.val.compareTo(node.val) < 0)) {
T temp = node.val;
node.val = node.parent.val;
node.parent.val = temp;
node = node.parent;
}
}
private TreeNode<T> findNode(int pos) {
TreeNode<T> node = this;
int reversed = 1;
while(pos > 0) {
reversed <<= 1;
reversed |= (pos&1);
pos >>= 1;
}
reversed >>= 1;
while(reversed > 1) {
if((reversed & 1) == 0) {
node = node.left;
} else {
node = node.right;
}
reversed >>= 1;
}
return node;
}
public TreeNode<T> remove(int pos) {
if(pos <= 1) {
return null;
}
TreeNode<T> last = findNode(pos);
if(last.parent.right == last) {
last.parent.right = null;
} else {
last.parent.left = null;
}
this.val = last.val;
bubbleDown();
return null;
}
public void bubbleDown() {
TreeNode<T> node = this;
do {
TreeNode<T> left = node.left;
TreeNode<T> right = node.right;
if(left != null && right != null) {
T max = left.val.compareTo(right.val) > 0 ? left.val : right.val;
if(max.compareTo(node.val) > 0) {
if(left.val.equals(max)) {
left.val = node.val;
node.val = max;
node = left;
} else {
right.val = node.val;
node.val = max;
node = right;
}
} else {
break;
}
} else if(left != null) {
T max = left.val;
if(left.val.compareTo(node.val) > 0) {
left.val = node.val;
node.val = max;
node = left;
} else {
break;
}
} else {
break;
}
} while(true);
}
}
private TreeNode<K> root;
private int position;
PriorityQ(){
this.position = 1;
}
public void insert(K val) {
if(val == null) {
return;
}
if(root == null) {
this.position = 1;
root = new TreeNode<K>(val);
this.position++;
return ;
}
root.insert(val, position);
position++;
}
public K remove() {
if(root == null) {
return null;
}
K val = root.val;
root.remove(this.position-1);
this.position--;
if(position == 1) {
root = null;
}
return val;
}
public static void main(String[] args) {
PriorityQ<Integer> q = new PriorityQ<>();
System.out.println(q.remove());
q.insert(1);
q.insert(11);
q.insert(111);
q.insert(1111);
q.remove();
q.remove();
q.remove();
q.remove();
q.insert(2);
q.insert(4);
}
}

Categories