Sunday, February 26, 2017


String Intern example

public class TestString {

    public static void main(String[] args) {
        String s1 = "Test";
        String s2 = "Test";
        String s3 = new String("Test");
        final String s4 = s3.intern();
        System.out.println(s1 == s2);
        System.out.println(s2 == s3);
        System.out.println(s3 == s4);
        System.out.println(s1 == s3);
      
      System.out.println("Inter string return string pool reference");
        System.out.println(s1 == s4);

        System.out.println(s1.equals(s2));
        System.out.println(s2.equals(s3));
        System.out.println(s3.equals(s4));
        System.out.println(s1.equals(s4));
        System.out.println(s1.equals(s3));
    }

}


//Output
true
false
false
false
true
true
true
true
true
true

Friday, February 10, 2017


insert element at middle in Doubly Link List Implementation

 /* Function to insert element at position */
    public void insertAtPos(int val , int pos)
    {
        Node nptr = new Node(val, null, null);    
        if (pos == 1)
        {
            insertAtStart(val);
            return;
        }            
        Node ptr = start;
        for (int i = 2; i <= size; i++)
        {
            if (i == pos)
            {
                Node tmp = ptr.getLinkNext();
                ptr.setLinkNext(nptr);
                nptr.setLinkPrev(ptr);
                nptr.setLinkNext(tmp);
                tmp.setLinkPrev(nptr);
            }
            ptr = ptr.getLinkNext();            
        }
        size++ ;
    }

for more details Click Here

Doubly linked list implementation in java
import java.util.NoSuchElementException;
 
public class DoublyLinkedListImpl {
 
    private Node head;
    private Node tail;
    private int size;
     
    public DoublyLinkedListImpl() {
        size = 0;
    }
    /**
     * this class keeps track of each element information
     * @author java2novice
     *
     */
    private class Node {
        E element;
        Node next;
        Node prev;
 
        public Node(E element, Node next, Node prev) {
            this.element = element;
            this.next = next;
            this.prev = prev;
        }
    }
    /**
     * returns the size of the linked list
     * @return
     */
    public int size() { return size; }
     
    /**
     * return whether the list is empty or not
     * @return
     */
    public boolean isEmpty() { return size == 0; }
     
    /**
     * adds element at the starting of the linked list
     * @param element
     */
    public void addFirst(E element) {
        Node tmp = new Node(element, head, null);
        if(head != null ) {head.prev = tmp;}
        head = tmp;
        if(tail == null) { tail = tmp;}
        size++;
        System.out.println("adding: "+element);
    }
     
    /**
     * adds element at the end of the linked list
     * @param element
     */
    public void addLast(E element) {
         
        Node tmp = new Node(element, null, tail);
        if(tail != null) {tail.next = tmp;}
        tail = tmp;
        if(head == null) { head = tmp;}
        size++;
        System.out.println("adding: "+element);
    }
     
    /**
     * this method walks forward through the linked list
     */
    public void iterateForward(){
         
        System.out.println("iterating forward..");
        Node tmp = head;
        while(tmp != null){
            System.out.println(tmp.element);
            tmp = tmp.next;
        }
    }
     
    /**
     * this method walks backward through the linked list
     */
    public void iterateBackward(){
         
        System.out.println("iterating backword..");
        Node tmp = tail;
        while(tmp != null){
            System.out.println(tmp.element);
            tmp = tmp.prev;
        }
    }
     
    /**
     * this method removes element from the start of the linked list
     * @return
     */
    public E removeFirst() {
        if (size == 0) throw new NoSuchElementException();
        Node tmp = head;
        head = head.next;
        head.prev = null;
        size--;
        System.out.println("deleted: "+tmp.element);
        return tmp.element;
    }
     
    /**
     * this method removes element from the end of the linked list
     * @return
     */
    public E removeLast() {
        if (size == 0) throw new NoSuchElementException();
        Node tmp = tail;
        tail = tail.prev;
        tail.next = null;
        size--;
        System.out.println("deleted: "+tmp.element);
        return tmp.element;
    }
     
    public static void main(String a[]){
         
        DoublyLinkedListImpl dll = new DoublyLinkedListImpl();
        dll.addFirst(10);
        dll.addFirst(34);
        dll.addLast(56);
        dll.addLast(364);
        dll.iterateForward();
        dll.removeFirst();
        dll.removeLast();
        dll.iterateBackward();
    }
}

Wednesday, February 8, 2017


Inserting a node to a given position in a linked list

Node InsertNth(Node head, int data, int position) {
    Node newNode = new Node();
    newNode.data = data;
    newNode.next = null;

    if (head == null) {
        return newNode;
    }
    if (position == 0) {
        newNode.next = head;
        head = newNode;
        return head;
    }
    Node prev = null;
    Node current = head;
    int i = 0;
    while (current !=null && i < position) {
        prev = current;
        current = current.next;
        i++;
    }
    newNode.next = prev.next;
    prev.next = newNode;
    return head;
}

Tuesday, February 7, 2017


SinglyLinkList implementation is java
public class LinkListImplementation {
 public static void main(String[] args) throws java.lang.Exception {
  LinkedListT a = new LinkedListT();
  a.addAtBegin(5);
  a.addAtBegin(15);
  a.addAtEnd(20);
  a.addAtEnd(21);
  a.deleteAtBegin();
  a.deleteAtEnd();
  a.addAtIndex(10, 2);
  a.addAtEnd(15);
  a.display();
  System.out.println("\n Size of the list is: " + a.size);
  System.out.println(" Element at 2nd position : " + a.elementAt(2));
  System.out.println(" Searching element 20, location : " + a.search(15));
 }
}

class Node {
 public int data;
 public Node next;

 public Node(int data) {
  this.data = data;
  this.next = null;
 }
}


class LinkedListT {
 public Node head;
 public int size;
 public LinkedListT() {
  head = null;
 }
 public void addAtBegin(int data) {
  Node n = new Node(data);
  n.next = head;
  head = n;
  size++;
 }
 public int deleteAtBegin() {
  int tmp = head.data;
  head = head.next;
  size--;
  return tmp;
 }
 public void deleteAtEnd() {
  Node currNode = head;
  if (head.next == null) {
   head = null;
  } else {
   while (currNode.next.next != null) {
    currNode = currNode.next;
   }
   int temp = currNode.next.data;
   currNode.next = null;
   size--;
  }
 }
 public void addAtEnd(int data) {
  if (head == null) {
   addAtBegin(data);
  } else {
   Node n = new Node(data);
   Node currNode = head;
   while (currNode.next != null) {
    currNode = currNode.next;
   }
   currNode.next = n;
   size++;
  }
 }
 public int elementAt(int index){
  if(index>size){
   return -1;
  }
  Node n = head;
  while(index-1!=0){
   n=n.next;
   index--;
  }
  return n.data;
 }
 public int getSize(){
  return size;
 }
 public int search(int data){
  Node n = head;
  int count = 1;
  while(n!=null){
   if(n.data==data){
    return count;
   }else{
    n = n.next;
    count++;
   }
  }
  return -1;
 }
 public void addAtIndex(int data, int position){
  if(position == 1){
   addAtBegin(data);
  }
  int len = size;
  if (position>len+1 || position <1){
   System.out.println("\nINVALID POSITION");
  }
  if(position==len+1){
   addAtEnd(data);
  }
  if(position<=len && position >1){
   Node n = new Node(data);
   Node currNode = head; //so index is already 1
   while((position-2)>0){
    System.out.println(currNode.data);
    currNode=currNode.next;
    position--;
   }
   n.next = currNode.next;
   currNode.next = n;
   size++;
  }
 }
 public void display() {
  System.out.println("");
  Node currNode = head;
  while (currNode != null) {
   System.out.print("->" + currNode.data);
   currNode = currNode.next;
  }
 }
}

Sunday, February 5, 2017


Stack Implementation By using an Array
package com.javadev.ds.stack;

public class MyStackImpl {
 
    private int stackSize;
    private int[] stackArr;
    private int top;
 
    /**
     * constructor to create stack with size
     * @param size
     */
    public MyStackImpl(int size) {
        this.stackSize = size;
        this.stackArr = new int[stackSize];
        this.top = -1;
    }
 
    /**
     * This method adds new entry to the top
     * of the stack
     * @param entry
     * @throws Exception
     */
    public void push(int entry) throws Exception {
        if(this.isStackFull()){
            throw new Exception("Stack is already full. Can not add element.");
        }
        System.out.println("Adding: "+entry);
        this.stackArr[++top] = entry;
    }
 
    /**
     * This method removes an entry from the
     * top of the stack.
     * @return
     * @throws Exception
     */
    public int pop() throws Exception {
        if(this.isStackEmpty()){
            throw new Exception("Stack is empty. Can not remove element.");
        }
        int entry = this.stackArr[top--];
        System.out.println("Removed entry: "+entry);
        return entry;
    }
     
    /**
     * This method returns top of the stack
     * without removing it.
     * @return
     */
    public int peek() {
        return stackArr[top];
    }
 
    /**
     * This method returns true if the stack is
     * empty
     * @return
     */
    public boolean isStackEmpty() {
        return (top == -1);
    }
 
    /**
     * This method returns true if the stack is full
     * @return
     */
    public boolean isStackFull() {
        return (top == stackSize - 1);
    }
 
    public static void main(String[] args) {
        MyStackImpl stack = new MyStackImpl(5);
        try {
            stack.push(4);
            stack.push(8);
            stack.push(3);
            stack.push(89);
            stack.pop();
            stack.push(34);
            stack.push(45);
            stack.push(78);
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        try {
            stack.pop();
            stack.pop();
            stack.pop();
            stack.pop();
            stack.pop();
            stack.pop();
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }
}
- See more at: http://www.java2novice.com/data-structures-in-java/stacks/introduction/#sthash.CrwOKKm1.dpuf

Wednesday, January 25, 2017


Matrix multiplication
import java.util.Scanner;

public class MatrixMultiplication {

   public static void main(String[] args) {
       Scanner s = new Scanner(System.in);
       System.out.print("Enter number of rows in A: ");
       int rowsInA = s.nextInt();
       System.out.print("Enter number of columns in A / rows in B: ");
       int columnsInA = s.nextInt();
       System.out.print("Enter number of columns in B: ");
       int columnsInB = s.nextInt();
       int[][] a = new int[rowsInA][columnsInA];
       int[][] b = new int[columnsInA][columnsInB];
       System.out.println("Enter matrix A");
       for (int i = 0; i < a.length; i++) {
           for (int j = 0; j < a[0].length; j++) {
               a[i][j] = s.nextInt();
           }
       }
       System.out.println("Enter matrix B");
       for (int i = 0; i < b.length; i++) {
           for (int j = 0; j < b[0].length; j++) {
               b[i][j] = s.nextInt();
           }
       }
       int[][] c = multiply(a, b);
       System.out.println("Product of A and B is");
       for (int i = 0; i < c.length; i++) {
           for (int j = 0; j < c[0].length; j++) {
               System.out.print(c[i][j] + " ");
           }
           System.out.println();
       }
   }

   public static int[][] multiply(int[][] a, int[][] b) {
       int rowsInA = a.length;
       int columnsInA = a[0].length; // same as rows in B
       int columnsInB = b[0].length;
       int[][] c = new int[rowsInA][columnsInB];
       for (int i = 0; i < rowsInA; i++) {
           for (int j = 0; j < columnsInB; j++) {
               for (int k = 0; k < columnsInA; k++) {
                   c[i][j] = c[i][j] + a[i][k] * b[k][j];
               }
           }
       }
       return c;
   }
}