This is a simple program of LinkedList that is implemented in Java Programming.Basic operation are add,remove and traversing LinkedList.
Example :
public class LinkedList<E> {
private Node<E> first = null;
private Node<E> last = null;
private int size = 0;
static class Node<E> {
Node<E> prev;
Node<E> next;
E element;
Node(Node<E> prev, E value, Node<E> next) {
this.prev = prev;
this.next = next;
this.element = value;
}
}
public void add(E element) {
final Node<E> l = last;
final Node<E> newNode = new Node<E>(l, element, null);
last = newNode;
if (l == null) {
first = newNode;
} else {
l.next = newNode;
}
size++;
}
public void traverse() {
Node<E> node = first;
while (node.next != null) {
node = node.next;
System.out.print(node.element + " ");
}
}
public void remove(int index) {
unlink(node(index));
}
private void unlink(Node<E> node) {
Node<E> prev = node.prev;
Node<E> next = node.next;
if (prev == null) {
first = next;
} else {
prev.next = next;
node.prev = null;
}
if (next == null) {
last = prev;
} else {
next.prev = prev;
node.next = null;
}
node.element = null;
size--;
}
public int size() {
return size;
}
private Node<E> node(int index) {
if (index < (size >> 1)) {
Node<E> node = first;
for (int i = 0; i < index; i++) {
node = node.next;
}
return node;
} else {
Node<E> node = last;
for (int i = size - 1; i > index; i--) {
node = node.prev;
System.out.println(node.element);
}
return node;
}
}
public static void main(String args[]) {
LinkedList<Integer> list = new LinkedList<>();
list.add(234);
list.add(345);
list.add(45);
list.add(2);
list.add(5);
list.add(86);
list.add(23);
list.add(897);
list.add(4345);
list.add(65);
list.traverse();
System.out.println(" ");
list.remove(5);
list.traverse();
}
}
No comments:
Post a Comment