Linked List implementation in Java
This is a simple implementation of linked list in java.
=====
package collections;
public class LinkedListMyImpl {
Node startNode;
Node endNode;
void add(int i){
if(startNode == null){
Node n = new Node();
n.i = i;
startNode = n;
}else{
Node n = new Node();
n.i = i;
if(endNode == null){
startNode.nextNode = n;
endNode = n;
endNode.previousNode = startNode;
}else{
endNode.nextNode = n;
n.previousNode = endNode;
endNode = n;
}
}
}
void remove(int i){
Node n = startNode;
while( n != null){
if(n.i == i){
Node previousNode = n.previousNode;
Node nextNode = n.nextNode;
if(previousNode != null)
previousNode.nextNode = nextNode;
if(nextNode != null)
nextNode.previousNode = previousNode;
n = null;
break;
}
if(n.nextNode != null)
n = n.nextNode;
}
}
void print(){
Node n = startNode;
while( n != null){
System.out.println(n.i);
n = n.nextNode;
}
}
public static void main(String[] args) {
LinkedListMyImpl i = new LinkedListMyImpl();
i.add(1);
i.add(2);
i.add(3);
i.add(4);
i.add(5);
i.add(6);
i.add(7);
i.add(8);
i.print();
System.out.println("======================");
i.remove(4);
i.print();
System.out.println("======================");
i.remove(8);
i.print();
}
}
class Node{
int i;
Node previousNode;
Node nextNode;
}
=====
=====
package collections;
public class LinkedListMyImpl {
Node startNode;
Node endNode;
void add(int i){
if(startNode == null){
Node n = new Node();
n.i = i;
startNode = n;
}else{
Node n = new Node();
n.i = i;
if(endNode == null){
startNode.nextNode = n;
endNode = n;
endNode.previousNode = startNode;
}else{
endNode.nextNode = n;
n.previousNode = endNode;
endNode = n;
}
}
}
void remove(int i){
Node n = startNode;
while( n != null){
if(n.i == i){
Node previousNode = n.previousNode;
Node nextNode = n.nextNode;
if(previousNode != null)
previousNode.nextNode = nextNode;
if(nextNode != null)
nextNode.previousNode = previousNode;
n = null;
break;
}
if(n.nextNode != null)
n = n.nextNode;
}
}
void print(){
Node n = startNode;
while( n != null){
System.out.println(n.i);
n = n.nextNode;
}
}
public static void main(String[] args) {
LinkedListMyImpl i = new LinkedListMyImpl();
i.add(1);
i.add(2);
i.add(3);
i.add(4);
i.add(5);
i.add(6);
i.add(7);
i.add(8);
i.print();
System.out.println("======================");
i.remove(4);
i.print();
System.out.println("======================");
i.remove(8);
i.print();
}
}
class Node{
int i;
Node previousNode;
Node nextNode;
}
=====
Comments