Monday, May 19, 2014

How to create a Singly Linked List in Java

I have started revisiting Java Basics during my summer break and currently trying to figure out the famous "Linked List".In this post we will learn about various types of linked list by using code and figures because having a visual always helps in understanding a concept.
Singly Linked List 
The node in a singly linked list comprises of  :-
- info  that stores the text or information about the node
pointer  that stores the reference to the next node.
Each linked list has a head which is usually the first element in the list and a tail which is usually null in case of singly linked list.

Singly Linked  List
The above weird looking figure is the in memory representation of a linked list,where the top part stores the info and the bottom part stores the reference to the next node it points to.Head is the first element in list and tail is usually null.The problem with singly linked list is that it can only be traversed in forward direction so you need to store the reference to its first element in a separate data structure and then traverse it node by node in forward direction by using that data structure.
JAVA CODE FOR CREATING,PRINTING SINGLY LINKED LIST

public class createLinkedList<T>{
/* Node Definition
* data stores the information about the node
* next stores the node to which current node points to
*/
private T data;
private createLinkedList<T> next;

public createLinkedList(T value){
data=value;
}
public createLinkedList<T> next(){
return next;
}
public T getValue() {
return data;
}
/*
* Setter methods for data and next
*/
public void setValue(T data){
this.data=data;
}
public void setNext(createLinkedList<T> next){
this.next=next;
}

public static void main(String[] args) {
createLinkedList<Integer> node1=new createLinkedList<Integer>(12);
createLinkedList<Integer> node2=new createLinkedList<Integer>(3);
createLinkedList<Integer> node3=new createLinkedList<Integer>(-8);
createLinkedList<Integer> node4=new createLinkedList<Integer>(6);
node1.setValue(node1.getValue());
node1.setNext(node2);
node2.setValue(node2.getValue());
node2.setNext(node3);
node3.setValue(node3.getValue());
node3.setNext(node4);
node4.setValue(node4.getValue());
node4.setNext(null);

/*
*Printing linked list
*/
createLinkedList<Integer> referenceToList=node1;
while(referenceToList!=null ){
System.out.println(referenceToList.getValue());
referenceToList=referenceToList.next();

}


}
}

No comments:

Post a Comment