Monday, January 25, 2016

Implementation of Binary Tree in Java

package BinaryTree;

public class BinaryTreeNode {

public int data;
public BinaryTreeNode left;
public BinaryTreeNode right;

public BinaryTreeNode(int data) {
this.data = data;
left = null;
right = null;
}

public int getData() {
return data;
}

public void setData(int data) {
this.data = data;
}

public BinaryTreeNode getLeft() {
return left;
}

public void setLeft(BinaryTreeNode left) {
this.left = left;
}

public BinaryTreeNode getRight() {
return right;
}

public void setRight(BinaryTreeNode right) {
this.right = right;
}

public String toString(BinaryTreeNode root) {
String result = "[";

while(root.getLeft()!=null){
result = result + root.getData();
}

while(root.getRight()!=null){
result = result + root.getData();
}

result+="]";
return result;
}

/* public String toString() {
String result = "";
result = result+"--" + data + "Left Child:-" + left + "Right Child:-" + right + "\n";
return result;
}*/
}




package BinaryTree;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Stack;



public class testBinaryTree {
int diameter = 0;
int left, right;

public BinaryTreeNode insertBinartTree(BinaryTreeNode root, int data) {
if (root == null) {
return null;
}
Queue<BinaryTreeNode> q = new LinkedList<BinaryTreeNode>();
q.offer(root);
while (!q.isEmpty()) {
BinaryTreeNode tmp = q.poll();
/**
* here both if condition working parallel.
*/
if (tmp != null) {
if (tmp.getLeft() != null)
q.offer(tmp.getLeft());
else {
tmp.left = new BinaryTreeNode(data);
return root;
}
}
if (tmp.getRight() != null) {
q.offer(tmp.right);
} else {
tmp.right = new BinaryTreeNode(data);
return root;
}
}

return root;
}

}

Reverse Linked List Recursive in Java

package DataStructures;

public class LinkedListReverse {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub

LinkedList linkedList = new LinkedList(5);
linkedList.next = new LinkedList(4);
linkedList.next.next = new LinkedList(3);
linkedList.next.next.next = new LinkedList(2);
linkedList.next.next.next.next = new LinkedList(1);
System.out.println("original linked list:-" + linkedList.toString());
linkedList = recursiveReverse(linkedList);
System.out.println("Recursively reverse:-" + linkedList.toString());

reverseListIterative(linkedList);

}

public static LinkedList recursiveReverse(LinkedList linkedList) {
if (linkedList == null || linkedList.next == null) {
return linkedList;
}
LinkedList remainingReverse = recursiveReverse(linkedList.next);
LinkedList current = remainingReverse;
while (current.next != null) {
current = current.next;
}
current.next = linkedList;
linkedList.next = null;
return remainingReverse;

}

}

Reverse Linked List Node In Java

    //Utility function to reverse the given list
      //Ex: Input : 1->2->3
      //Output : 3->2->1
      static ListNode reverse(ListNode list){
             if(list == null)
                   return null;

             ListNode current = list, previous = null, forward;
             while(current != null){
                    forward = current.next;
                    current.next = previous;
                    previous = current;
                    current = forward;
             }
             return previous;
      }

Add Two Linked List Data in Java




Input:
  First List: 5->6->3  // represents number 365
  Second List: 8->4->2 //  represents number 248
Output
  Resultant list: 3->1->6  // represents number 613

 public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
      int carry =0;

       ListNode newHead = new ListNode(0);
       ListNode p1 = l1, p2 = l2, p3=newHead;

       while(p1 != null || p2 != null){
           if(p1 != null){
               carry += p1.getData();
               p1 = p1.next;
           }

           if(p2 != null){
               carry += p2.getData();
               p2 = p2.next;
           }

           p3.next = new ListNode(carry%10);
           p3 = p3.next;
           carry /= 10;
       }

       if(carry==1)
           p3.next=new ListNode(1);

       return newHead.next;
   }

Reverse K nodes in Java



Example:
Inputs:  1->2->3->4->5->6->7->8->NULL and k = 3 
Output:  3->2->1->6->5->4->8->7->NULL. 

Inputs:   1->2->3->4->5->6->7->8->NULL and k = 5
Output:  5->4->3->2->1->8->7->6->NULL. 



public ListNode reverseKnodes(ListNode head, int k) {
ListNode current = head;
ListNode prevTail = null;
ListNode prevCurrent = head;
while (current != null) {
int count = k;
ListNode tail = null;
while (current != null && count > 0) {
ListNode next = current.getNext();
current.setNext(tail);
tail = current;
current = next;
count--;
}
if (prevTail != null) {
prevTail.setNext(tail);
} else {
head = tail;
}
prevTail = prevCurrent;
prevCurrent = current;
}
return head;

}

Find Loop Exists in linkedList in Java








Image result for loop exists linked list java







public boolean findIfLoopExists(ListNode head) {
ListNode fastPrt = head;
ListNode slowPtr = head;
while (fastPrt != null && fastPrt.getNext() != null) {
fastPrt = fastPrt.getNext().getNext();
slowPtr = slowPtr.getNext();
if (slowPtr == fastPrt) {
return true;
} else {
return false;
}
}
return false;
}

Merge Two Sorted List in java



public ListNode mergeTwoSortedList(ListNode head1, ListNode head2){
ListNode head = new ListNode(0);
ListNode current = head;
while(head1!= null && head2!= null){
if(head.getData() <= head2.getData()){
current.next = head1;
head1 = head1.getNext();
}
else{
current.next = head2;
head2 = head2.getNext();
}
}
if(head1!= null){
current.next = head1;
}
else if(head2!= null){
current.next = head2;
}

return head.next;
}

Is LinkedList Even in Java




public int isLinkedListEven(ListNode head){
while(head!= null && head.getNext()!= null){
head = head.getNext().getNext();
}
if(head == null){
return 0;
}
else{
return 1;
}
}

Find Intersection Node of two Linked List


   



public int findIntersectingNode(ListNode list1, ListNode list2){
int L1 = 0,L2=0,diff = 0;

ListNode head1 = list1;
ListNode head2 = list2;

while(head1 != null){
L1++;
head1 = head1.getNext();
}

while(head2!=null){
L2++;
head2 = head2.getNext();
}

if(L1<L2){
head1 = list2;
head2 = list1;
diff = L2-L1;
}
else{
head1 = list1;
head2 = list2;
diff = L1-L2;
}
for(int i = 0; i<diff; i++){
head1 = head1.getNext();
}
while(head1!=null && head2!=null){
if(head1 == head2){
return head1.getData();
}
head1 = head1.getNext();
head2 = head2.getNext();
}
return Integer.MAX_VALUE;
}

Print linked List Value from end in java





public void printListFromEnd(ListNode head){

if(head == null){
return;
}
printListFromEnd(head.getNext());
System.out.println(head.getData());
}

Find Middle element of Linked list in java




public ListNode findMiddle(ListNode head){
ListNode ptr1x,ptr2x;
ptr1x = ptr2x = head;
int i = 0;

while(ptr1x.getNext()!=null){
if(i == 0){
ptr1x = ptr1x.getNext();
i = 1;
}
else{
ptr1x = ptr1x.getNext();
ptr2x = ptr2x.getNext();
i = 0;
}
}

return ptr2x;
}

Find Middle element of Linked List in java




public void findMiddleNode(ListNode head){
ListNode p,q;
Hashtable<Integer, ListNode> table = new Hashtable<Integer, ListNode>();
int i = 1;
int length = 0;
for(p = head; (q = p.getNext())!= null; p =q){
/**
* here first I am getitng next node then adding to hash Table just to
* avoid adding the address of head Node
*/
p = p.getNext();
table.put(i, p);
i++;
length++;
}

int midData = length/2;

//System.out.println("Hash table is:-"+table);
System.out.println("Middle element is:-"+table.get(midData).getData());
}

Find Nth Node From End in likedList in Java




    Input    1--->2---->3-----4--->5------>6


find 4 position from  end...

public void findNthNodeFromEnd(ListNode head, int NthPosition){
ListNode p,q;
Hashtable<Integer, ListNode> table = new Hashtable<Integer, ListNode>();
int i = 1;
int length = 0;
for(p = head; (q = p.getNext())!= null; p =q){
/**
* here first I am getitng next node then adding to hash Table just to
* avoid adding the address of head Node
*/
p = p.getNext();
table.put(i, p);
i++;
length++;
}

//System.out.println("Hash table is:-"+table);
System.out.println(NthPosition+":-position form end is:-"+table.get((length-NthPosition)+1).getData());
}

Find Nth Node From end In linkedList IN Java


input     1---->2--->3---6>----7--->null

find 3rd node in linked list

public ListNode NthNodeFromEnd(ListNode head, int NthNode) {
ListNode ptemp = head;
ListNode pNthNode = null;
for (int i = 1; i < NthNode; i++) {
ptemp = ptemp.getNext();
}
while (ptemp != null) {
if (pNthNode == null) {
pNthNode = head;
} else {
pNthNode = pNthNode.getNext();
}
ptemp = ptemp.getNext();
}
return pNthNode;
}

Reverse Linkedlist Pair Iterative in Java


input        1-->2-->3---->4--->null

Output    2--->1---->4---->3---->null

public ListNode ReversePairIterative(ListNode head) {
ListNode temp1 = null;
ListNode temp2 = null;
while (head != null && head.next != null) {
if (temp1 != null) {
temp1.next.next = head.next;
}
temp1 = head.next;
// System.out.println("temp1--" + temp1.getData());
head.next = head.next.next;
// System.out.println("head.next--" + head.next.getData());
temp1.next = head;
// System.out.println("temp1.next--" + temp1.next.getData());
if (temp2 == null) {
temp2 = temp1;
}
head = head.next;
// System.out.println("head--" + head.getData());
}
return temp2;
}

Reverse Queue First K Elements inJava


public void reverseQueueFirstKElement(int k, Queue<Integer> q) {
if (q == null || k > q.size()) {
throw new IllegalArgumentException();
} else if (k > 0) {
Stack<Integer> s = new Stack<Integer>();
for (int i = 0; i < k; i++) {
s.push(q.remove());
}
while (!s.isEmpty()) {
q.add(s.pop());
}
for (int i = 0; i < q.size() - k; i++) {
q.add(q.remove());
}
}
}

Double Ended Queue implementation in Java

package Queue;

import java.util.ArrayList;
import java.util.List;

public class DoubleEndedQueueImpl {

    private List<Integer> deque = new ArrayList<Integer>();
   
    public void insertFront(int item){
        //add element at the beginning of the queue
        System.out.println("adding at front: "+item);
        deque.add(0,item);
        System.out.println(deque);
    }
   
    public void insertRear(int item){
        //add element at the end of the queue
        System.out.println("adding at rear: "+item);
        deque.add(item);
        System.out.println(deque);
    }
   
    public void removeFront(){
        if(deque.isEmpty()){
            System.out.println("Deque underflow!! unable to remove.");
            return;
        }
        //remove an item from the beginning of the queue
        int rem = deque.remove(0);
        System.out.println("removed from front: "+rem);
        System.out.println(deque);
    }
   
    public void removeRear(){
        if(deque.isEmpty()){
            System.out.println("Deque underflow!! unable to remove.");
            return;
        }
        //remove an item from the beginning of the queue
        int rem = deque.remove(deque.size()-1);
        System.out.println("removed from front: "+rem);
        System.out.println(deque);
    }
   
    public int peakFront(){
        //gets the element from the front without removing it
        int item = deque.get(0);
        System.out.println("Element at first: "+item);
        return item;
    }
   
    public int peakRear(){
        //gets the element from the rear without removing it
        int item = deque.get(deque.size()-1);
        System.out.println("Element at rear: "+item);
        return item;
    }
   
    public static void main(String a[]){
       
        DoubleEndedQueueImpl deq = new DoubleEndedQueueImpl();
        deq.insertFront(34);
        deq.insertRear(45);
        deq.removeFront();
        deq.removeFront();
        deq.removeFront();
        deq.insertFront(21);
        deq.insertFront(98);
        deq.insertRear(5);
        deq.insertFront(43);
        deq.removeRear();
    }
}

Priority Queue Implementation in Java

package Queue;

public class PriorityQueueImpl {

    @SuppressWarnings("rawtypes")
private Comparable[] pQueue;
    private int index;
   
    public PriorityQueueImpl(int capacity){
        pQueue = new Comparable[capacity];
    }
   
    public void insert(Comparable<Integer> item ){
        if(index == pQueue.length){
            System.out.println("The priority queue is full!! can not insert.");
            return;
        }
        pQueue[index] = item;
        index++;
        System.out.println("Adding element: "+item);
    }
   
    @SuppressWarnings("unchecked")
    public Comparable<?> remove(){
        if(index == 0){
            System.out.println("The priority queue is empty!! can not remove.");
            return null;
        }
        int maxIndex = 0;
        // find the index of the item with the highest priority
        for (int i=1; i<index; i++) {
            if (pQueue[i].compareTo (pQueue[maxIndex]) > 0) {
                maxIndex = i;
            }
        }
        Comparable<?> result = pQueue[maxIndex];
        System.out.println("removing: "+result);
        // move the last item into the empty slot
        index--;
        pQueue[maxIndex] = pQueue[index];
        return result;
    }
   
    public static void main(String a[]){
        PriorityQueueImpl pqi = new PriorityQueueImpl(5);
        pqi.insert(34);
        pqi.insert(23);
        pqi.insert(5);
        pqi.insert(87);
        pqi.insert(32);
       

        pqi.remove();
        pqi.remove();
        pqi.remove();
        pqi.remove();
        pqi.remove();
    }
}

Implement Queue using two stack

package Queue;

import java.util.Stack;

public class QueueWithTwoStacks<T> {

Stack<T> s1 = new Stack<T>();
Stack<T> s2 = new Stack<T>();

public void enqueue(T data) {
s1.push(data);
}

public T dequeue() {
if (s2.empty()) {
while (!s1.isEmpty()) {
s2.push(s1.pop());
}

}
return s2.pop();
}

}

Implement Stack using two queues

package Queue;

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

public class StackWithTwoQueues<T> {
public Queue<T> q1 = new LinkedList<T>();
public Queue<T> q2 = new LinkedList<T>();

public void push(T data) {
if (q1.isEmpty()) {
q1.offer(data);
} else {
q2.offer(data);
}
}

public T pop() {
int i = 0, size;
if (q2.isEmpty()) {
size = q1.size();
while (i < size - 1) {
q2.offer(q1.poll());
i++;
}
return q1.poll();
} else {
size = q2.size();
while (i < size - 1) {
q1.offer(q2.poll());
i++;
}
}
return q2.poll();
}

public void showStackData(){
while(!q1.isEmpty()){
System.out.print(q1.poll()+" ");
}
while(!q2.isEmpty()){
System.out.print(q2.poll()+" ");
}
}
public static void main(String[] args) {
StackWithTwoQueues<Integer> obj = new StackWithTwoQueues<Integer>();
obj.push(5);
obj.push(6);
obj.push(7);
obj.push(8);
//obj.showStackData();

while(obj!=null){
System.out.print(obj.pop()+" ");
}

/*System.out.print(obj.pop()+" ");
System.out.print(obj.pop()+" ");
System.out.print(obj.pop()+" ");
System.out.print(obj.pop()+" ");*/
}

}

Sort stack Value and Print



public DynamicArrayStack sort(DynamicArrayStack str) throws Exception{
DynamicArrayStack s1 = new DynamicArrayStack(5);
while(!str.isEmpty()){
int temp = str.pop();
while(!s1.isEmpty() && s1.peek()>temp){
str.push(s1.pop());
}
s1.push(temp);

}
return s1;

}

Print Stack Value in reverse



public void stackReverse(DynamicArrayStack stack) throws Exception{
if(stack.isEmpty()){
return;
}
DynamicArrayStack s1 = new DynamicArrayStack(5);
while(!stack.isEmpty()){
int temp = stack.pop();
s1.push(temp);
}
System.out.println(s1);

}

Check String is palindrome using Stack

Input String "ababXbaba"

public boolean isPalindrome(String inputStr) throws Exception {
char inputChar[] = inputStr.toCharArray();
DynamicArrayStack s = new DynamicArrayStack(4);
int i = 0;
while (inputChar[i] != 'X') {
s.push(inputChar[i]);
i++;
}
i++;
while (i < inputChar.length) {
if (s.isEmpty()) {
return false;
}

if (inputChar[i] != (s.pop())) {
return false;
}
i++;
}
return true;
}

Stack Implementation Using Linked List

package Stack;

import LinkedList.ListNode;

public class LinkedStack<T> {

public int length;
public ListNode top;

public LinkedStack(){
length = 0;
top = null;
}

public void push(int data){
ListNode temp = new ListNode(data);
temp.setNext(top);
top = temp;
length++;
}

public int pop(){
int result = top.getData();
System.out.println(result);
top = top.getNext();
length--;
return result;
}

public int peek(){
int result = top.getData();
return result;
}

public boolean isEmpty(){
return (length == 0);
}

public int size(){
return length;
}

public String toString(){
String result = "[";
ListNode current = top;
while(current!= null){
result = result+current.getData()+",";
current = current.getNext();
}
result+="]";
return result;
}

public static void main(String[] args) {

LinkedStack<Integer> obj = new LinkedStack<Integer>();
obj.push(1);
obj.push(3);
obj.push(3);

System.out.println(obj);
obj.pop();
}
}

Queue Implementation using Linked List In Java

package Queue;

import LinkedList.ListNode;

public class LinkedQueue {

public int length;
public ListNode front, rear;

public LinkedQueue() {
length = 0;
front = rear = null;
}

public boolean isEmpty() {
return (length == 0);
}

public void enqueue(int data) {
ListNode node = new ListNode(data);
if (isEmpty()) {
front = node;
} else {
rear.setNext(node);
}
rear = node;
length++;
}

public int dequeue() throws Exception {
if (isEmpty()) {
throw new Exception("queue");
}
int result = front.getData();
front = front.getNext();
System.out.println(result);
length--;
return result;
}

public int first() throws Exception {
if (isEmpty()) {
throw new Exception();
}
return front.getData();
}

public int size() {
return length;
}

public String toString() {
String result = "[";
ListNode current = front;
while (current != null) {
result = result + current.getData() + ",";
current = current.getNext();
}
result+="]";
return result;

}

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

queue.enqueue(5);
queue.enqueue(9);
queue.enqueue(7);
queue.enqueue(10);
queue.enqueue(1);
queue.enqueue(2);
queue.enqueue(3);
System.out.println(queue);
queue.dequeue();
queue.dequeue();
queue.dequeue();
queue.dequeue();
queue.dequeue();
queue.dequeue();

}

}

Queue Implementation In java

package Queue;

import Stack.DynamicArrayStack;

public class DynamicArrayQueue {

private int[] queueRep;
private int front, size, rear;
private static int CAPACITY = 4;
public static int MINCAPACITY = 1 << 15;

DynamicArrayQueue() {
queueRep = new int[CAPACITY];
front = 0;
size = 0;
rear = 0;
}

DynamicArrayQueue(int cap) {
queueRep = new int[cap];
front = 0;
size = 0;
rear = 0;
}

public void enQueue(int data) {
if (size == CAPACITY)
expand();
size++;
queueRep[rear] = data;
rear = (rear+1) % CAPACITY;
}

public int deQueue() {
size--;
int data = queueRep[front % CAPACITY];
queueRep[front] = Integer.MIN_VALUE;
front = (front + 1) % CAPACITY;
return data;
}

public int size() {
return size;
}

public boolean isEmpty() {
return (size == 0);
}

public boolean isFull() {
return (size == CAPACITY);
}

public void expand() {
int length = size();
int[] newQueue = new int[length << 1];
System.out.println("rear"+rear);
for (int i = front; i <= rear; i++){
System.out.println(queueRep[i]);
//here i- front to just make 0 value
newQueue[i - front] = queueRep[i % CAPACITY];
}
queueRep = newQueue;
front = 0;
rear = size - 1;
CAPACITY *= 2;
}

public DynamicArrayQueue queueReversal(DynamicArrayQueue queue) throws Exception{
DynamicArrayStack stack = new DynamicArrayStack(5);
while(!queue.isEmpty()){
stack.push(queue.deQueue());
}
while(!stack.isEmpty()){
queue.enQueue(stack.pop());
}
return queue;
}

public String toString() {
String result = "[";
for (int i = 0; i < size; i++) {
result += Integer.toString(queueRep[(front + i) % CAPACITY]);
if (i < size - 1) {
result += ",";
}
}
result += "]";
return result;
}

public static void main(String[] args) {
DynamicArrayQueue obj = new DynamicArrayQueue();
obj.enQueue(1);
obj.enQueue(2);
obj.enQueue(3);


System.out.println(obj);
//obj.deQueue();
//obj.deQueue();
System.out.println(obj);

}
}

Stack Implementaion in java

package Stack;

public class DynamicArrayStack {

public int capacity;

public static final int CAPACITY = 16;
public static int MINCAPACITY = 1 << 15;

public int[] stackRep;
public int top = -1;

public DynamicArrayStack(int cap) {
capacity = cap;
stackRep = new int[capacity];
}

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

public boolean isEmpty() {
return (top < 0);
}

public void push(int data) {
if (size() == capacity) {
expand();
}
stackRep[++top] = data;
}

public void expand() {
int length = size();
int[] newStack = new int[length << 1];
System.arraycopy(stackRep, 0, newStack, 0, length);
stackRep = newStack;
}

public void shrink() {
int length = top + 1;
if (length <= MINCAPACITY || top << 2 >= length) {
return;
}
length = length + (top << 1);
if (top < MINCAPACITY) {
length = MINCAPACITY;
}
int[] newStack = new int[length];
System.arraycopy(stackRep, 0, newStack, 0, top + 1);
stackRep = newStack;
}

public int top() throws Exception {
if (isEmpty()) {
throw new Exception("Stack is Empty");
}
return stackRep[top];
}

public int peek(){
return stackRep[top];
}

public int pop() throws Exception {
int data;
if (isEmpty()) {
throw new Exception("Stack is empty");
}
data = stackRep[top];
stackRep[top--] = Integer.MIN_VALUE;
return data;
}

Circular Linked List Implementation in Java

package LinkedList;

public class CLLNode {
public int data;
public CLLNode next;

CLLNode(int data){
this.data = data;
}
public int getData() {
return data;
}
public void setData(int data) {
this.data = data;
}
public CLLNode getNext() {
return next;
}
public void setNext(CLLNode next) {
this.next = next;
}


}


package LinkedList;

public class CircularLinkedList {
public CLLNode tail;
public int length;

CircularLinkedList() {
tail = null;
length = 0;
}

public void add(int data) {
addToHead(data);
}

public void addToHead(int data) {
CLLNode temp = new CLLNode(data);
if (tail == null) {
tail = temp;
tail.setNext(tail);
} else {
temp.setNext(tail.getNext());
tail.setNext(temp);
}
length += 1;
}

public void addToTail(int data) {
CLLNode temp = new CLLNode(data);
if (tail == null) {
tail = temp;
tail.setNext(tail);
} else {
temp.setNext(tail.getNext());
tail.setNext(temp);
}
tail = tail.getNext();
length += 1;
}

public int peek() {
return tail.getNext().getData();
}

public int tailPeek() {
return tail.getData();
}

public int removeFromHead() {
CLLNode temp = tail.getNext();
if (tail == tail.getNext()) {
tail = null;
} else {
tail.setNext(temp.getNext());
temp.setNext(null);
}
length--;
return temp.getData();
}

public int removeFromTail() {
CLLNode finger = tail;
while (finger.getNext() != tail) {
finger = finger.getNext();
}

CLLNode temp = tail;
if (finger == tail) {
tail = null;
} else {
finger.setNext(tail.getNext());
tail = finger;
}
length--;
return temp.getData();
}

public boolean contains(int data) {
if (tail == null) {
return false;
}
CLLNode finger;
finger = tail.getNext();
while (finger != tail && (!(finger.getData() == data))) {
finger = finger.getNext();
}
return finger.getData() == data;
}

public int remove(int data) {
if (tail == null) {
return Integer.MIN_VALUE;
}
CLLNode finger = tail.getNext();
CLLNode previous = tail;
int compares;
for (compares = 0; compares < length && (!(finger.getData() == data)); compares++) {
previous = finger;
finger = finger.getNext();
}
if (finger.getData() == data) {
if (tail == tail.getNext()) {
tail = null;
} else {
previous.setNext(previous.getNext().getNext());
}
finger.setNext(null);
length--;
return finger.getData();
} else {
return Integer.MIN_VALUE;
}

}

public int size() {
return length;
}

public int lenght() {
return length;
}

public boolean isEmpty() {
return tail == null;
}

public void clear() {
length = 0;
tail = null;
}

public String toString() {
String result = "[";
if (tail == null) {
return result + "]";
}
result = result + tail.getData();
CLLNode temp = tail.getNext();
while (temp != tail) {
result = result + "," + temp.getData();
temp = temp.getNext();
}
return result + "]";

}
public static void main(String[] args) {
CircularLinkedList obj = new CircularLinkedList();
obj.add(5);
obj.add(6);
obj.add(7);
obj.add(8);
System.out.println("Original CircularLinkedlist"+obj);
System.out.println("tail data:-"+obj.tailPeek());
obj.addToTail(9);
System.out.println("After addition to tail:-"+obj.tailPeek());
System.out.println("After addition to tail CircularLinkedlist"+obj);
}

}

Doubly linked Implementaions In Java

package LinkedList;

public class DLLNode {
private int data;
DLLNode prev;
DLLNode next;

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

public DLLNode(int data,DLLNode prev,DLLNode next){
this.data = data;
this.prev = prev;
this.next = next;
}

public int getData(){
return data;
}

public void setData(int data){
this.data = data;
}

public DLLNode getPrev(){
return prev;
}

public void setPrev(DLLNode where){
prev = where;
}

public DLLNode getNext(){
return next;
}

public void setNext(DLLNode where){
next = where;
}

}


package LinkedList;

public class DoublyLinkedList {
private DLLNode head;
private DLLNode tail;
private int length;

public DoublyLinkedList() {
head = new DLLNode(90, null, null);
tail = new DLLNode(Integer.MAX_VALUE, head, null);
head.setNext(tail);
length = 0;
}

public int getPosition(int data) {
DLLNode temp = head;
int pos = 0;
while (temp != null) {
if (temp.getData() == data) {
return pos;
}
pos += 1;
temp = temp.getNext();
}
return Integer.MIN_VALUE;
}

public int length() {
return length;
}

public void insert(int data) {
DLLNode newNode = new DLLNode(data, head, head.getNext());
newNode.getNext().setPrev(newNode);
head.setNext(newNode);
length += 1;
}

public void insert(int data, int Position) {

if (Position < 0) {
Position = 0;
}
if (Position > length) {
Position = length;
} else if (Position == 0) {
DLLNode temp = new DLLNode(data);
temp.next = head;
head = temp;
}
else {
DLLNode temp = head;
for (int i = 1; i < Position; i++) {
temp = temp.getNext();
}
DLLNode newNode = new DLLNode(data);
newNode.next = temp.next;
newNode.prev = temp;
newNode.next.prev = newNode;
temp.next = newNode;
length += 1;
}
}

public String toString() {
String result = "[]";
if (length == 0) {
return result;
}
result = "[" + head.getNext().getData();
DLLNode temp = head.getNext().getNext();
while (temp != null) {
result += "," + temp.getData();
temp = temp.getNext();
}
return result + "]";
}

public void insertTail(int newValue) {
DLLNode newNode = new DLLNode(newValue, tail.getPrev(), tail);
newNode.getPrev().setNext(newNode);
tail.setPrev(newNode);
length += 1;
}

public void remove(int position) {
DLLNode temp = head;
for (int i = 1; i < position; i++) {
temp = temp.getNext();
}
temp.getNext().setPrev(temp.getPrev());
temp.getPrev().setNext(temp.getNext());
length -= 1;
}
public int removeTail(){
if(length == 0){
return Integer.MAX_VALUE;
}
DLLNode save = tail.getPrev();
tail.setPrev(save.getPrev());
save.getPrev().setNext(tail);
return save.getData();
}

public static void main(String[] args) {
DoublyLinkedList obj = new DoublyLinkedList();
obj.insert(5);
obj.insert(8);
obj.insert(9);
obj.insert(6);
obj.insert(2);
obj.insert(7);
System.out.println("Before doubly linked list:-"+obj);
System.out.println("position:-" + obj.getPosition(5));
System.out.println("remove tail:-"+obj.removeTail());

System.out.println("After remove from tail doubly linked list becomes:-"+obj);
System.out.println("remove tail:-"+obj.removeTail());
System.out.println("After remove from tail doubly linked list becomes:-"+obj);
/*obj.insert(10, 2);
System.out.println("----------");
System.out.println(obj);*/
System.out.println("head data:-"+obj.head.getData());
System.out.println("head next data:-"+obj.head.getNext().getData());
System.out.println("####################################");
System.out.println("position:-"+obj.getPosition(7));
obj.remove(2);
System.out.println(obj);
}
}