Thursday, 12 February 2015

Single Link List Java Implementation ...

Single Link List: One of the basic data structure which teach us how to store the data in the memory so that it can be picked with the minimum effort by the device. 

    Link list is a data establishment pattern which keep the data in such a manner that form one data node you can either reach to the end or go through the path. Link list creates a path and arrange data so that its easy to pick any data from any place in the memory. Link list is one of the idea to create a chain by arranging data in required manner.

     One node keeps the address of another and this process goes on till either data is no more or memory is no more. Single Link List can have multiple method to serve the purpose. These methods can be ...

add(): Adds data node from the starting and it adds node at the end of the list.
insertAt():  Insert a data node at desired place.
deleteAt(): Delete a node with data from any place you wish.
length(): This method can help you finding the number of node in the list.
deleteAll(): This method can be created to make the list empty.

Above are some of the key methods which get used frequently. You can write your own method as per your requirement.

Implementation: We have got a class called Node which act as a memory box which contains value and address of the next node. Once a node is created for the first time that node is being referred as Head Node and this node will be node till it gets deleted by other method. when other node is being created and ready to add further and head node keeps address of its node. This process goes on till we want to stop add process. Similarly when we try to insert a node in between nodes we first need to reach at the node then we can create a node and play with the address part involved in the node. Please check the code. Same process need to be addressed for deletion from a specific place. Last but not the least length, to find the no of node in the list we need to iterate through the list till next node becomes null and counter variable will store the each iteration count.


/*  Class that implements Link List concept in java */



package com.ds.linklist;

import com.ds.common.Node;


public class SingleLinkList
{
         Node head;

         public SingleLinkList()
         {
                 head = null;
         }

         public SingleLinkList(int val)
         {
                 head = new Node(val);
         }

         /**
          * Adds value to the list and adding means obviously at the end of the list
          */
         public void add(int val) throws Exception
         {
                 head = LinkListUtil.getInstance().add(val, head);
         }

         /**
          * Inserts value to the list at give position and if position is greater
          * than current size of the list then add this node at the end of the list
          */
         public void insertAt(int position, int val) throws Exception
         {
                  // Check the length of existing list, if position is greater than the
                  // size then add value to the list at the end of the list
                  int len = length();

                  if (position > (len + 1)) {
                           position = len + 1;
                  }

                  if (position == 1) {
                           // If user wants to insert a value at first position then this block
                           // will be executed
                           Node insertedNode = new Node(val);

                           insertedNode.next = head;
                           head = insertedNode;
                  } else {
                           int i = 2;
                           boolean isNotAdded = true;

                            Node currentNode = head;

                            while (currentNode.next != null) {
                                     if (i == position) {
                                           Node insertedNode = new Node(val);

                                           insertedNode.next = currentNode.next;
                                           currentNode.next = insertedNode;
                                           isNotAdded = false;
                                     }
                                     currentNode = currentNode.next;
                                     i++;
                            }

                            // Below block will be executed when position is greater than the
                            // size
                            // This block of code adds the value at the end of the list
             
                            if (isNotAdded) {
                                    Node insertedNode = new Node(val);

                                    currentNode.next = insertedNode;
                            }
                  }
         }

         /**
          * Deletes the value at the given position in the list
          */
         public void deleteAt(int position) throws Exception
         {
                   int len = length();

                   if (position > (len)) {
                            position = len;
                   }

                   if (position == 1) {
                            head = head.next;
                   } else {
                            int i = 1;
                            Node tmpNode = head;

                            while (head != null) {
                                      if (i == position - 1) {
                                              head.next = head.next.next;
                                              head = tmpNode;
                                              break;
                                      }
                                      head = head.next;
                                      i++;
                            }
                   }

         }

         /**
          * Gets the length of the list i.e. no of node in this list
          */
         public int length() throws Exception
         {
                    int len = LinkListUtil.getInstance().length(head);

                    return len;
         }

         /**
          * Prints all the nodes value in the list
          */

         public void print() throws Exception
         {
                   Node tmpNode = head;

                   while (tmpNode != null) {
                           System.out.print(tmpNode.data + " -> ");
                           tmpNode = tmpNode.next;
                   }
                   System.out.println("");
         }

         /**
          * Deletes all the nodes with give values from the list
          */
         private void deleteAll(final int value)
         {
                   Node tmpNode = head;
                   Node prevNode = null;

                   while (tmpNode != null) {
                          if (tmpNode.data == value) {
                                  if (tmpNode == head) {
                                             head = head.next;
                                  } else {
                                             prevNode.next = tmpNode.next;
                                  }
                          } else {
                                  prevNode = tmpNode;
                          }
                          tmpNode = tmpNode.next;
                   }

         }

         public static void main(String[] arg) throws Exception
         {
                  SingleLinkList list = new SingleLinkList();

                  list.add(3);
                  list.add(2);
                  list.add(7);

                  list.insertAt(3, 5);
                  list.insertAt(4, 10);
                  list.insertAt(8, 15);

                  list.deleteAt(1);
                  list.deleteAt(3);
                  list.deleteAt(8);

                  list.insertAt(9, 9);
                  list.insertAt(9, 2);

                  list.print();
                  list.deleteAll(2);
                  list.print();

                  System.out.println("link list size issss   " + list.length());
         }
}


// Below class is used to carry node data ... may be used in same class file or in different class file

package com.ds.common;

public class Node
{
         public Integer data;
         public Node next;

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

Wednesday, 11 February 2015

Stack - Array Java Implementation ...

Stack: Stack is the data structure which works on the concept of LIFO (Last In First Out). Consider one real time example of stack ... lets assume there is a box in which i keep books one over another. So if i want to take book out of the box then the book which enters last in the box gets out first from the box. Stack data structure can be implemented with two ideas one using Array and another using Link List. Now lets discuss concept of Stack implementation using Array. Here we are going to create an array which dynamically grows by twice its size.

Here we have got some frequently used methods. Now here we go ...


push(): Pushes data into the stack.
pop():  Removes data from the stack. 
top(): Method delivers top element of the stack.
isEmpty(): This method returns true id stack is empty and false if not.
length(): This method returns integer value as the no of elements of the stack.


other method implementation is available in the Stack implementation in below class definition which violates the concept of stack. This method is sort().

Implementation: 
                               We have got an Array with 5 as its size. We define a variable as top and this variable gets initialized by -1 and when we push element into the stack we place this value at the 0th location so before inserting element into the stack we increment the top variable by one the top becomes 0 and we place the value into stack and same process goes on till the stack is full.
      Once stack is full we have to do a process to increase the size of stack and we can achieve by creating an array with double the size of the array and we copy stack elements into the newly created array so once again we have got enough space in new array. We can do the implementation by incrementing its size by fixed size such as 5 rather than doubling the size of the array. Doubling the size will take more space but incrementing the size of array by fixed number will take more time as we may need to copy it more frequently. Now which implementation you choose will be based on your requirement, if you have enough resources (memory) then we have to go with the bigger size array.

Challenges:

  • We may have got Stack Full Exception, if we have not implemented dynamic incrementation. As we have got an Array which grows as per need, we will never face Stack Full Exception.
  • We will get another type of Exception, i.e. Stack Empty Exception, if we get pop() method call again and again. Once the stack is empty i.e no more element to remove then we can display Stack Empty Exception.

/*
      This class creates a dynamically growing stack. This class starts with array size 5 but once this stack array gets full this class grows by double its size. Growing a stack can be increased by desired no of size.

*/

package com.ds.stack;

public class StackArray
{
         Integer[] stack;
         public int top;

         public StackArray() 
         {
                stack = new Integer[5];
                top = -1;
          }

          public void push(int value)
          {
                 int arrLen = stack.length;

                 if (top == arrLen - 1) {
                         copyArray(arrLen);
                 }
                 stack[++top] = value;
          }

          public int pop()
          {
                  if (top == -1) {
                          System.out.println("Stack is empty");
                          return -1;
                  }
                  int poppedElement = stack[top];
                  stack[top--] = null;

                  return poppedElement;
          }

          public Integer top()
          {
                  int lastIndex = (stack.length) - 1;
                  Integer top = null;

                  for (int i = lastIndex; i >= 0; i--) {
                           Integer arrayVal = stack[i];
                          
                           if (arrayVal != null) {
                                     top = arrayVal;
                                     break;
                           }
                  }
                  return top;
          }

          public boolean isEmpty()
          {
                  int len = stack.length;

                  for (int i = 0; i < len; i++) {
                           if (stack[i] != null) {
                                   return false;
                           }
                  }
                  return true;
          }

          public int length()
          {
                  return top + 1;
          }

          public Integer[] sort(StackArray stack)
          {
                   StackArray tmpStack = new StackArray();
               
                   while (!stack.isEmpty()) {
                            int tmp = stack.pop();
                          
                            while (!tmpStack.isEmpty() && tmpStack.top() > tmp) {
                                      int poppedElement = tmpStack.pop();
                                      stack.push(poppedElement);
                            }
                            tmpStack.push(tmp);
                   }
                   stack.stack = tmpStack.stack;
                   return tmpStack.stack;
          }

          private void copyArray(int len)
          {
                   Integer[] dummyStack = new Integer[len * 2];

                   for (int i = 0; i < len; i++) {
                         dummyStack[i] = stack[i];
                   }
                   stack = dummyStack;
          }

          private void printStack(Integer[] stackArray)
          {
                   int arrLen = stackArray.length;
                   String printString = "";

                   for (int i = 0; i < arrLen; i++) {
                          Integer arrayVal = stackArray[i];
        
                          if (arrayVal == null) {
                                 break;
                          }
                          printString += arrayVal.toString() + " --> ";
                   }

                   if ("".equals(printString)) {
                          System.out.println("Stack is empty");
                   } else {
                          System.out.println(printString);
                   }
          }

          public static void main(String[] args) throws Exception
          {
                     StackArray stack = new StackArray();

                     stack.push(4);
                     stack.push(3);
                     stack.push(5);
                     stack.push(7);
                     stack.push(2);
                     stack.push(1);
                     stack.printStack(stack.stack);

                     //stack.sort(stack);
                     stack.pop();
                     stack.pop();
                     stack.pop();

                     stack.printStack(stack.stack);
                     System.out.println("Length of the stack is   " + stack.length() + "    top element is   " + stack.top() + "  top index  "+stack.top);
          }

}


Comparison:  We got to compare both the implementation i.e. Array implementation and Link List implementation. Lets discuss both the implementation then you will be in better position to decide which implementation is better. 

Array: Array implementation takes constant time for push(), pop(), top(), length() as we have got top variable which gives us the exact location of the element for pop(), push() and other described methods. The only problem with this concept is when we have to use dynamic array we need n time to copy the elements in new array which has been created to eliminate Stack Full Exception. 
      If we have the scenario where the total no of element count is fixed then array implementation of stack is preferable over Link List implementation of Stack.

Link List: Link list implementation need n time for every push(), pop() and other operation as we need to iterate form the first node to the last node where element needs to be push(), pop() or other operations. So here we have got the idea of both the concepts and based on the scenario we need to use for better performance.

Stack - Link List Java Implementation ...

Stack:  Stack is the data structure which works on the concept of LIFO (Last In First Out). Consider one real time example of stack ... lets assume there is a box in which i keep books one over another. So if i want to take book out of the box then the book which enters last in the box gets out first from the box. Stack data structure can be implemented with two ideas one using Array and another using Link List. Now lets discuss concept of Stack implementation using Link List. Implementation using link list will have an edge over Array implementation, we don't need to worry about the size of the stack as far as we have memory available in the machine we can create node to push the element. You will never face Stack Full Exception.

Here we have got some frequently used methods. Now here we go ...


push(): Pushes data into the stack.
pop():  Removes data from the stack. 
top(): Method delivers top element of the stack.
isEmpty(): This method returns true id stack is empty and false if not.
length(): This method returns integer value as the no of elements of the stack.


other method implementation is available in the Stack implementation in below class definition which violates the concept of stack. This method is sort().

Implementation: 
                  We have got a class called Node which act as a memory box which contains value and address of the next node. Once a node is created for the first time that node is being referred as Head Node and this node will be node till it gets deleted by other method. when other node is being created and ready to push further and head node keeps address of its node. This process goes on till we want to stop push process. Please check the code. Same process need to be addressed for pop method. Last but not the least length, to find the no of node in the list we need to iterate through the list till next node becomes null and counter variable will store the each iteration count. For getting top node we need to iterate again to get the top node of the stack. There is very thin line between Link List and Stack.

Challenges:

  • We will never get Stack Full Exception as node is getting created at run time and there is no size specification available. So there is no chance to get this exception.
  • We will get another type of Exception, i.e. Stack Empty Exception, if we get pop() method call again and again. Once the stack is empty i.e no more element to remove then we can display Stack Empty Exception.

package com.ds.stack;

import com.ds.common.Node;

public class StackList
{
 Node head;

 public StackList() {
head = null;
 }

 public void push(int value) throws Exception
 {
head = add(value, head);
 }

         public Node add(int val, Node head)
         {
                Node tmpNode = head;

                 if (head == null) {
                         tmpNode = head = new Node(val);
                 } else {
                         while (tmpNode.next != null) {
                                  tmpNode = tmpNode.next;
                         }
                         tmpNode.next = new Node(val);
                 }
                 return head;

         }

 public void top() throws Exception
  {
   if (head == null) {
     System.out.println("Stack is empty");
   } else {
    Node tmpNode = head;
    Node topNode = null;

    while (tmpNode != null) {
       topNode = tmpNode;
      tmpNode = tmpNode.next;
    }
    System.out.println(topNode.data);
   }
 }

public void pop() throws Exception
{
Node tmpNode = head;
Node prevNode = null;
Node nxtNode = head.next;

while (nxtNode != null) {
prevNode = tmpNode;
nxtNode = nxtNode.next;
tmpNode = tmpNode.next;
}

if (prevNode != null) {
prevNode.next = null;
} else {
head = null;
}
}

/**
* Prints all the nodes value in the list
*/
public void print() throws Exception
{
if (head != null) {
Node tmpNode = head;

        while (tmpNode != null) {
            System.out.print(tmpNode.data + " -> ");
            tmpNode = tmpNode.next;
        }
        System.out.println("");
} else {
System.out.println("Stack is empty");
}
}

/**
* Gets the length of the stack i.e. no of node in this list
*/
public int length() throws Exception
{
int len = 0;
                Node currentNode = head;

                while (currentNode != null) {
                        currentNode = currentNode.next;
                        len++;
                }
return len;
}

public static void main(String[] args) throws Exception
{
StackList stack = new StackList();

stack.push(2);
stack.push(5);
stack.push(8);
stack.push(3);
stack.push(7);

stack.top();

System.out.println("link list size is     " + stack.length());

stack.print();

stack.pop();
stack.pop();
stack.pop();

stack.print();
stack.top();

stack.pop();
stack.pop();

stack.print();

stack.top();
System.out.println("link list size is   " + stack.length());
}
}



//  Node class needs to be created separately

// Node Class specification is below

package com.ds.common;

public class Node
{
        public Integer data;
        public Node next;

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

}



Comparison:  
We got to compare both the implementation i.e. Array implementation and Link List implementation. Lets discuss both the implementation then you will be in better position to decide which implementation is better. 

Array: Array implementation takes constant time for push(), pop(), top(), length() as we have got top variable which gives us the exact location of the element for pop(), push() and other described methods. The only problem with this concept is when we have to use dynamic array we need n time to copy the elements in new array which has been created to eliminate Stack Full Exception. 
      If we have the scenario where the total no of element count is fixed then array implementation of stack is preferable over Link List implementation of Stack.

Link List: Link list implementation need n time for every push(), pop() and other operation as we need to iterate form the first node to the last node where element needs to be push(), pop() or other operations. So here we have got the idea of both the concepts and based on the scenario we need to use for better performance.