Showing posts with label Data Structures. Show all posts
Showing posts with label Data Structures. Show all posts

Friday, April 22, 2016

Level Order Traversal in a Binary Tree from Bottom to Top

    public void LevelOrderReverse()    {
        System.out.println(LevelOrderReverse(this));
    }
    private String LevelOrderReverse(BinarySearchTree T)    {
        StringBuffer sb = new StringBuffer();
        if(T!=null)    {
            Queue<BinarySearchTree> Q = new LinkedList<BinarySearchTree>();
            Stack<BinarySearchTree> S = new Stack<BinarySearchTree>();
            Q.add(T);
            while(Q.size() > 0)    {
                BinarySearchTree C = Q.remove();
                if (C.right != null)
                    Q.add(C.right);
                if (C.left != null)
                    Q.add(C.left);
                S.push(C);
            }
            while(S.size() > 0)
                sb.append(S.pop().data).append(", ");
        }
        return sb.toString();
    }

Wednesday, April 20, 2016

Amazon Question: Print Last N nodes of Linked List in reverse

Given a singly linked list's head and an integer N, print last N nodes of the list in reverse order.
Example:
List = 1->2->3->4->5->6->7->8
N = 3
Output = 8, 7, 6,

    public void printRev(int count)    { // count = N
        temp = count;

// this here is the head node
        System.out.println(printRev(this, new StringBuffer()));
    }
    private int temp;
    private String printRev(LinkedList L, StringBuffer sb)    {
        if(L.next!=null)
            printRev(L.next, sb);
        if(temp>0)    {
            sb.append(L.data).append(", ");
            temp--;
        }
        return sb.toString();
    }

Saturday, December 19, 2015

Inserting an Array of Elements in a Linked List

    public void insert(int... data)    {
        LinkedList L = this;
        while(L.next!=null)    {
            L=L.next;
        }
        int size=data.length;
        for(int i=0; i<size; i++)    {
            L.next=new LinkedList(data[i]);
            L=L.next;
        }
    }

Tuesday, December 15, 2015

Find if a Tree is a Mirror copy of another Tree

    public boolean isMirrorTrees(BinaryTree T1, BinaryTree T2)    {
        if(T1==null && T2==null)
            return true;
        if(T1.data!=T2.data)
            return false;
        if((T1==null && T2!=null) || (T2==null && T1!=null))
            return false;
        if(isMirrorTrees(T1.left, T2.right)
                && isMirrorTrees(T2.left, T1.right))
            return true;
        return false;
    }

Monday, December 14, 2015

get Root to given Node path in a Binary Tree

    public void rootToNode(int data)    {
        getRootToNodePath(this, data, new StringBuffer(), false);
    }
    private void getRootToNodePath(BinarySearchTree T, int data, StringBuffer sb, boolean isFound)    {
        if(T!=null && !isFound)    {
            sb.append(T.data).append(", ");
            if(T.data==data)    {
                System.out.println(sb.toString());
                isFound = true;
                return;
            }    else    {
                getRootToNodePath(T.left, data, new StringBuffer(sb), isFound);
                getRootToNodePath(T.right, data, new StringBuffer(sb), isFound);
            }
        }

    }

Check if two Binary Tree are same

    public boolean isTreesSame(BinaryTree T1, BinaryTree T2)    {
        if(T1==null && T2==null)
            return true;
        if(T1==null || T2==null)
            return false;
        if(T1.data==T2.data
                && isTreesSame(T1.left, T2.left)
                && isTreesSame(T1.right, T2.right))
            return true;
        return false;
    }

Sunday, December 13, 2015

Delete Node from Binary Search Tree

// Binary Search Tree full program is available here: link

    private BinarySearchTree ParentNode; //Parent Node of the node to delete


    private boolean LeftOrRightFlag; //Deleting node is Left from parent means true, else Right means false


    public void DeleteNode(int data)    {
        DeleteNode(this, data);
    }
    private void DeleteNode(BinarySearchTree T, int data)    {
        if(T==null) return;
        if(data==T.data)    {    //delete root note
            T.data=getMin(T.right).data;
            DeleteNode(T.right, T.data);
        }    else    {
            BinarySearchTree Current = findNode(T, data);
            if(Current.left==null && Current.right==null)
                if(LeftOrRightFlag)
                    ParentNode.left=null;
                else
                    ParentNode.right=null;
            else if(Current.left==null)
                if(LeftOrRightFlag)
                    ParentNode.left=Current.right;
                else
                    ParentNode.right=Current.right;
            else if(Current.right==null)
                if(LeftOrRightFlag)
                    ParentNode.left=Current.left;
                else
                    ParentNode.right=Current.left;
            else    {//Current node has both children
                Current.data=getMin(Current.right).data;
                DeleteNode(T.right, Current.data);
            }
        }
    }


    private BinarySearchTree getMin(BinarySearchTree T)    {
        while(T.left!=null)
            T=T.left;
        return T;
    }


    public BinarySearchTree findNode(BinarySearchTree T,int data)    {    //except root
        if(data==T.data)
            return T;
        else if(data<T.data)    {
            ParentNode=T;
            LeftOrRightFlag=true;
            return findNode(T.left, data);
        }    else    {
            ParentNode=T;
            LeftOrRightFlag=false;
            return findNode(T.right, data);
        }
    }

Saturday, December 12, 2015

is Binary Tree a Binary Search Tree

    public boolean isBinarySearchTree()    {
        return isBinaryTree(this, (-10^23), 10^23);
    }
    private boolean isBinarySearchTree(BinaryTree T, int min, int max)    {
        if(T==null) return true;
        if(T.data>min && T.data<max
                && isBinaryTree(T.left, min, T.data)
                && isBinaryTree(T.right, T.data, max))
            return true;
        return false;
    }

Thursday, December 3, 2015

Make all diagonal to 0 when encountered a 0

Given a 2D array, write a method MakeDiagonalZeroWhenEncounteredZero() to convert all diagonal to zero when encountered a zero.

import java.util.ArrayList;

public class ChessBoard {
    public int[][] Board;
    public ChessBoard(int fill) { //Pass 1 for fill
        this.Board = new int[8][8];
        for(int i=0; i<8; i++)
            for(int j=0; j<8; j++)
                this.Board[i][j]=fill;
    }
    public void FillZero(int x, int y)    {
        if(x<8 && x>-1 && y<8 && y>-1)
            Board[x][y]=0;
        else
            System.out.println("Error: Possition Not Valid");
    }
    public void MakeDiagonalZeroWhenEncounteredZero()    {
        ArrayList<Coordinates> zeros = getZeroCordinates();
        for(Coordinates c: zeros)    {
            int x=c.getX();
            int y=c.getY();
            while(x<7 && y<7)    {
                x++; y++;
                Board[x][y]=0;
            }
            x=c.getX();    y=c.getY();
            while(x>0 && y>0)    {
                x--; y--;
                Board[x][y]=0;
            }
            x=c.getX();    y=c.getY();
            while(x<7 && y>0)    {
                x++; y--;
                Board[x][y]=0;
            }
            x=c.getX();    y=c.getY();
            while(x>0 && y<7)    {
                x--; y++;
                Board[x][y]=0;
            }
        }
    }
    private ArrayList<Coordinates> getZeroCordinates()    {
        ArrayList<Coordinates> zeros = new ArrayList<Coordinates>();
        for(int i=0; i<8; i++)
            for(int j=0; j<8; j++)    {
                if(Board[i][j]==0)
                    zeros.add(new Coordinates(i,j));
            }
        return zeros;
    }
    public void PrintBoard()    {
        for(int i=0; i<8; i++)    {
            StringBuffer sb = new StringBuffer();
            for(int j=0; j<8; j++)    {
                sb.append(Board[i][j]).append(", ");
            }
            System.out.println(sb.toString());
        }
    }
}
class Coordinates    {
    private int x, y;
    public Coordinates(int x, int y) {
        this.x = x;
        this.y = y;
    }
    public int getX() {
        return x;
    }
    public int getY() {
        return y;
    }
}





Main Method:
        ChessBoard cb = new ChessBoard(1);
        cb.FillZero(4, 5);
        cb.FillZero(7, 2);
        System.out.println("Input: ");
        cb.PrintBoard();
        cb.MakeDiagonalZeroWhenEncounteredZero();
        System.out.println("Output: ");
        cb.PrintBoard();

   
Input:
1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 0, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 0, 1, 1, 1, 1, 1,
Output:
1, 0, 1, 1, 1, 1, 1, 1,
1, 1, 0, 1, 1, 1, 1, 1,
1, 1, 1, 0, 1, 1, 1, 0,
1, 1, 1, 1, 0, 1, 0, 1,
1, 1, 1, 1, 1, 0, 1, 1,
0, 1, 1, 1, 0, 1, 0, 1,
1, 0, 1, 0, 1, 1, 1, 0,
1, 1, 0, 1, 1, 1, 1, 1,

Wednesday, December 2, 2015

Stack Implementation using two Queues

import java.util.LinkedList;
import java.util.Queue;

public class Stack {
    Queue<Integer> Q1,Q2;
    public Stack() {
        Q1=new LinkedList<Integer>();
        Q2=new LinkedList<Integer>();
    }
    public void push(int data)    {
        Q1.add(data);
    }
    public int peek()    {
        int size=Q1.size()-1;
        for(int i=0; i<size;i++)
            Q2.add(Q1.remove());
        int peek = Q1.remove();
        Q2.add(peek);
        SwapQueues();
        return peek;
    }
    public int pop()    {
        int size=Q1.size()-1;
        for(int i=0; i<size;i++)
            Q2.add(Q1.remove());
        int pop = Q1.remove();
        SwapQueues();
        return pop;
    }
    private void SwapQueues()    {
        Queue<Integer> temp = Q1;
        Q1=Q2;
        Q2=temp;
    }
}

Queue Implementation using Two Stacks

import java.util.Stack;

public class Queue {
    Stack<Integer> S1;
    Stack<Integer> S2;
    public Queue() {
        S1 = new Stack<Integer>();
        S2 = new Stack<Integer>();
    }
    public void enqueue(int data)    {
        S1.push(data);
    }
    private void ShiftS1toS2()    {
        while(!S1.isEmpty())
            S2.push(S1.pop());
    }
    public int dequeue()    {
        ShiftS1toS2();
        return S2.pop();
    }
    public int lookup()    {
        ShiftS1toS2();
        return S2.peek();
    }
}

Sort a Stack using one additional Stack

    public Stack<Integer> SortStack(Stack<Integer> input)    {
        if(input.isEmpty())    return input;
        Stack<Integer> buffer = new Stack<Integer>(); //Buffer Stack
        while(!input.isEmpty())    {
            int temp = input.pop();
            if(!buffer.isEmpty() && temp<buffer.peek())
                input.push(buffer.pop());
            buffer.push(temp);
        }
        return buffer;
    }



This Code doesn't work all the time
Input: [5, 7, 8, 9, 6, 0, 2]
Output: [0, 2, 6, 8, 7, 5, 9]

Monday, November 30, 2015

Check if Parentheses are Balanced


import java.util.Stack;

class Parenthesis    {
    public boolean isParenthesisCorrect(String s)    {
        char[] c = s.toCharArray();
        int size=c.length;
        Stack S = new Stack<Character>();
        boolean flag = true;
        for(int i=0; i<size; i++)    {
            if(c[i]=='(')
                S.push(c[i]);
            else if(c[i]==')')    {
                if(!((Character)S.pop()=='('))    {
                    flag=false;
                    break;
                }
            }
        }
        if(!S.isEmpty())
            flag=false;
        return flag;
    }
}

public class Main {
    public static void main(String[] args) {
        Parenthesis P = new Parenthesis();
        String s = "((a+b)*(a-b))/c";
        System.out.println(P.isParenthesisCorrect(s));
    }
}

Saturday, November 28, 2015

Implementing 3 fixed size Stacks using same Array

public class ThreeStacks {
    int ArraySize;
    int[] Array;
    int[] topPointers =  {-1,-1,-1};
    public ThreeStacks(int size) {
        this.ArraySize = size;
        this.Array = new int[size * 3];
    }
    public int peek(int StackNumber)    {
        if(topPointers[StackNumber-1]>-1)    {
            return Array[(ArraySize*StackNumber)+topPointers[StackNumber]];
        }    else    {
            System.out.println("Error: "+StackNumber+" is empty");
            return ErrorCode;
        }
    }
    public static final int ErrorCode = -999;
    public int pop(int StackNumber)    {
        StackNumber--;
        if(topPointers[StackNumber]>-1)    {
            int ret = Array[(ArraySize*StackNumber)+topPointers[StackNumber]];
            topPointers[StackNumber]--;
            return ret;
        }    else    {
            System.out.println("Error: "+StackNumber+" is empty");
            return ErrorCode;
        }
    }
    public void push(int data, int StackNumber)    {
        int maxSize = (ArraySize*StackNumber)-1;
        if(topPointers[StackNumber-1]<maxSize)    {
            topPointers[StackNumber-1]++;
            int nextLoc = (ArraySize*(StackNumber-1))+topPointers[StackNumber-1];
            Array[nextLoc]=data;
        }    else    {
            System.out.println("Stack "+StackNumber+" is full");
        }
    }
    public void print3Stacks()    {
        StringBuffer sb =new StringBuffer();
        for(int i=0; i<=topPointers[0]; i++)    {
            sb.append(Array[i]);
        }
        System.out.println(sb.toString());
        sb =new StringBuffer();
        for(int i=ArraySize; i<=ArraySize+topPointers[1]; i++)    {
            sb.append(Array[i]);
        }
        System.out.println(sb.toString());
        sb =new StringBuffer();
        for(int i=(ArraySize*2); i<=(ArraySize*2)+topPointers[2]; i++)    {
            sb.append(Array[i]);
        }
        System.out.println(sb.toString());
    }
}

Create and Detect Loop in Linked List

The Linked List program is available here: link

     public boolean isLoopExist()    {
        LinkedList L = this;
        LinkedList slow = L;
        LinkedList fast = L;
        boolean isLoop = false;
        while(fast.next!=null)    {
            slow=slow.next;
            fast=fast.next.next;
            if(slow==fast)    {
                isLoop = true;
                break;
            }
        }
        return isLoop;
    }
    public void createLoop(int index)    {
        LinkedList L = this;
        for(int i=2; i<index; i++)    {
            L=L.next;
        }
        LinkedList indexPrevNode = L;
        while(L.next!=null)    {
            L=L.next;
        }
        L.next=indexPrevNode.next;
    }

Stack Implementation using Linked List

This is a Stack Implementation using LinkedList in Java. As in Java we don't have pointers and hard to remove head node in a empty list, we are using a dummy head node.

public class Stack {
    Stack next;
    int data;
    private int size;
    public Stack() {
        this.size=-1;
        this.data=-999; //Garbage Value to denote Head
        this.next=null;
    }
    public Stack(int data) {
        this.data=data;
        this.next=null;
    }
    public void push(int... data)    {
        int s = data.length;
        for(int i=0; i<s; i++)
            push(data[i]);
    }
    public void push(int data)    {
        Stack S = this;
        if(size==-1)    {
            S.next=new Stack(data);
        }    else    {
            Stack newNode = new Stack(data);
            newNode.next=S.next; //Head is a dummy node here
            S.next=newNode;
        }
        size++;
    }
    public final static int ErrorCode = -999;
    public int pop()    {
        Stack S = this;
        if(size>-1)    {
            int value = S.next.data;
            S.next=S.next.next;
            size--;
            return value;
        }    else    {
            System.out.println("Error: Stack is Empty");
            return ErrorCode;
        }
    }
    public int size()    {
        return size;
    }
    public int peek()    {
        Stack S = this;
        if(size>-1)    {
            return S.next.data;
        }    else    {
            System.out.println("Error: Stack is Empty");
            return ErrorCode;
        }
    }
    public void printStack()    {
        Stack S = this;
        S=S.next; // first node is dummy
        StringBuffer sb = new StringBuffer();
        while(S!=null)    {
            sb.append(S.data).append(", ");
            S=S.next;
        }
        System.out.println(sb.toString());
    }
}

Friday, November 27, 2015

Stack implementation using Array

public class Stack {
    int[] array;
    private int top;
    private int size;
    public Stack(int size) {
        this.size=size;
        array = new int[size];
        top = -1;
    }
    public void push (int... data)    {
        int size = data.length;
        for(int i=0; i<size; i++)
            push(data[i]);
    }
    public void push (int data)    {
        if (top<size-1)    {
            top++;
            array[top]=data;
        }
    }
    public final static int ErrorCode = -999;
    public int pop()    {
        if(!isEmpty())    {
            int a = array[top];
            top--;
            return a;
        }    else return ErrorCode;
    }
    public int peek()    {
        return array[top];
    }
    public boolean isEmpty()    {
        if(top<0) return true;
        else    return false;
    }
    public void printArray()    {
        int size = top+1;
        StringBuffer sb = new StringBuffer();
        for(int i=0; i<size; i++)
            sb.append(array[i]).append(", ");
        System.out.println(sb.toString());   
    }
}

Thursday, November 26, 2015

LinkedList print kth to last element

This module returns kth to last element of a Linked List

    public String kthLastElement(int k)    {
        LinkedList L = this;
        for(int i=1; i<k; i++)    {
            L=L.next;
        }
        StringBuffer sb = new StringBuffer();
        while(L!=null)    {
            sb.append(L.data).append(", ");
            L=L.next;
        }
        return sb.toString();
    }

Check if a LinkedList is a Palindrome

Input:
LinkedList L = new LinkedList("HeleH");
L.printList();
System.out.println(L.isPalindrome());

Program:
import java.util.Stack;

public class LinkedList {
    int data;
    LinkedList next;
    private LinkedList(int data) {
        this.data=data;
        this.next=null;
    }
    public LinkedList(String data) {
        char[] a = data.toCharArray();
        int size=a.length;
        if(size>0)    {
            this.data=a[0];
            this.next=null;
            for(int i=1; i<size; i++)
                append(a[i]);
        }
    }
    public boolean isPalindrome()    {
        LinkedList L = this;
        Stack<Integer> S=new Stack<Integer>();
        LinkedList slow = L;
        LinkedList fast = L;
        while(fast!=null && fast.next!=null)    {
            S.push(slow.data);
            fast = fast.next.next;
            slow = slow.next;
        }
        boolean flag = true;
        if(fast!=null) //String has odd number of char
            slow = slow.next;
        while(slow!=null)    {
            if(slow.data!=S.pop())    {
                flag=false;
                break;
            }
            slow = slow.next;
        }
        return flag;
    }
    public void append(int data)    {
        LinkedList L = this;
        while(L.next!=null)
            L=L.next;
        L.next=new LinkedList(data);
    }
    public void printList()    {
        LinkedList L = this;
        StringBuffer sb = new StringBuffer();
        while(L!=null)    {
            sb.append((char)L.data);
            L=L.next;
        }
        System.out.println("String: "+sb.toString());
    }
}


This program also shows how to use an integer data linked list to store characters.

Wednesday, November 25, 2015

Reverse a Single Linked List in Java using Recursion

You can refer for Linked List in Java program here: link

This is a program to reverse a linked list using recursion.
    public String reverseList()    {
        return reverseList(this, new StringBuffer()).toString();
    }
    private StringBuffer reverseList(LinkedList L, StringBuffer sb)    {
        if(L!=null)    {
            reverseList(L.next, sb);
            sb.append(L.data).append(", ");
        }
        return sb;
    }
UA-39217154-2