File: LinkedList.java
------------------------------------------------------------------------------------------------
package org.developersbrain.solutions;
class Block<T>{
Block<T> prevNode;
Block<T> nextNode;
T t;
Block(T t){
this.t = t;
prevNode=null;
nextNode=null;
}
}
public class LinkedList<T> {
Block<T> tail;
Block<T> head;
LinkedList(){
head=null;
tail=null;
}
void add(T t){
Block<T> newBlock=new Block<T>(t);
if(head==null){
head=newBlock;
tail=newBlock;
}else{
if(tail.prevNode==null){
head=newBlock;
head.nextNode=tail;
tail.prevNode=head;
}else{
newBlock.nextNode=head;
head.prevNode=newBlock;
head=newBlock;
}
}
}
void deleteNode(T t){
Block<T> nodes=head;
while(nodes!=null){
if(nodes.t.equals(t)){
if(nodes.prevNode==null){
head=nodes.nextNode;
head.prevNode=null;
}else if(nodes.nextNode==null){
tail=nodes.prevNode;
tail.nextNode=null;
}else{
nodes.prevNode.nextNode=nodes.nextNode;
nodes.nextNode.prevNode=nodes.prevNode;
}
}
nodes=nodes.nextNode;
}
}
void traverseFromHead(){
Block<T> nodes=head;
while(nodes!=null){
System.out.println(nodes.t);
nodes=nodes.nextNode;
}
}
void traverseFromTail(){
Block<T> nodes=tail;
while(nodes!=null){
System.out.println(nodes.t);
nodes=nodes.prevNode;
}
}
}
File: MainClass.java
------------------------------------------------------------------------------------------------
package org.developersbrain.solutions;
import java.io.IOException;
public class MainClass {
public static void main(String[] args) throws IOException{
LinkedList<Integer> ll=new LinkedList<Integer>();
ll.add(10);
ll.add(20);
ll.add(50);
ll.add(100);
ll.add(150);
System.out.println("Doubly Linked List-Traverse From Head");
System.out.println("---------------------------------------");
ll.traverseFromHead();
System.out.println();
System.out.println("Doubly Linked List-Traverse From Tail");
System.out.println("---------------------------------------");
ll.traverseFromTail();
System.out.println();
System.out.println("Remove element from list - Value: 10");
System.out.println("---------------------------------------");
System.out.println();
ll.deleteNode(10);
System.out.println("After Removing element from List-Traverse From Head");
System.out.println("---------------------------------------");
ll.traverseFromHead();
}
}
Output:
-----------------------------------------------------------------------------
Doubly Linked List-Traverse From Head
---------------------------------------
150
100
50
20
10
Doubly Linked List-Traverse From Tail
---------------------------------------
10
20
50
100
150
Remove element from list - Value: 10
---------------------------------------
After Removing element from List-Traverse From Head
---------------------------------------
150
100
50
20
Comments
Post a Comment