Java Double Linked List in Generic Type
Double Linked List
/*
Tue Nov 20 09:45:31 2018
--------------------------------------------------------------------------------
Double linkedlist for generic type in Java
append()
addFront()
remove()
head node
tail node
middle node
toList()
print()
--------------------------------------------------------------------------------
*/
class MyNode{
MyNode left;
MyNode right;
T data;
public MyNode(T data){
this.data = data;
}
}
class LinkedList{
public MyNode head;
public MyNode tail;
public LinkedList(){
}
public void append(MyNode node){
if(tail == null){
head = tail = node;
}else{
tail.right = node;
node.left = tail;
tail = node;
}
}
public void addFront(MyNode node){
if(head == null){
head = tail = node;
}else{
MyNode tmp = head;
head = node;
head.right = tmp;
tmp.left = head;
}
}
public void remove(MyNode r){
if(head != null){
// remove first node
if(head == r){
MyNode tmp = head.right;
head = head.right;
if(head == null) // only one node
tail = head;
// more than one node
}else{
if(tail == r){ // last node, two or more nodes
tail = tail.left;
tail.right = null;
}else{
// There are nodes between r
MyNode left = r.left;
MyNode right = r.right;
left.right = right;
right.left = left;
}
}
}
}
public void print(){
MyNode tmp = head;
while(tmp != null){
Print.p(tmp.data);
tmp = tmp.right;
}
}
public ArrayList toList(){
ArrayList list = new ArrayList();
MyNode tmp = head;
while(tmp != null){
list.add(tmp.data);
tmp = tmp.right;
}
return list;
}
}