Thursday, November 30, 2017

LinkedList Implementation In Java Program

import java.util.NoSuchElementException;

public class LinkedlistImpl<E> {

    private Node head;
    private Node tail;
    private int size;

    public LinkedlistImpl() {
 size = 0;
    }

    private class Node {
 Node next;
 Node prev;
 E Element;

 public Node(E element, Node next, Node prev) {
     this.Element = element;
     this.next = next;
     this.prev = prev;
 }
    }

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

    public int size() {
 return size;
    }

    // Adding element at head point
    public void addElementFromHead(E element) {
 Node N = new Node(element, head, null);
 if (head != null) {
     head.prev = N;
 }
 head = N;
 if (tail == null) {
     tail = N;
 }
 size++;
 System.out.println("element added" + element);
    }

    // Adding element at tail point
    public void addElementFromTail(E element) {
 Node N = new Node(element, null, tail);
 if (tail != null) {
     tail.next = N;
 }
 tail = N;
 if (head == null) {
     head = N;
 }
 size++;
 System.out.println("element added" + element);
    }

    public void forward() {
 System.out.println("forward");
 Node tmp = head;
 while (tmp != null) {
     System.out.println(tmp.Element);
     tmp = tmp.next;
 }
    }

    public void backward() {
 System.out.println("backword");
 Node tmp = tail;
 while (tmp != null) {
     System.out.println(tmp.Element);
     tmp = tmp.prev;
 }
    }

    // Removing first element
    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;
    }

    // Removing last element
    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[] args) {
 LinkedlistImpl<Integer> list = new LinkedlistImpl<Integer>();
 list.addElementFromHead(20);
 list.addElementFromHead(30);
 list.addElementFromTail(40);
 list.addElementFromTail(50);
 list.forward();
 list.backward();
 list.removeFirst();
 list.removeLast();
    }
}

No comments: