Monday, December 16, 2013

LinkedList: Node creation and display example

package ds;

 * @author Rajdeep
 * Note
 * Creating the list:
 * 1. 'start' refers to the first node and 'now' is made to refer to the latest
 *   added node.
 * 2. after creating the first linkedlist object and assigning value,
 *   'start' points to it because we are checking for start==null
 *   'start' is null in first node addition only.
 *   'now' also points to it, this being the latest node.
 * 3. Second node onwards, start is never null, so control goes to else part.
 *   '' points to nothing because its of reference type.
 *   so assign '' to the newly created object after
 *   checking ''.
 * 4. Now 'start' pointed or the first object's (node's) 'next' part is linked
 *   to the 2nd object since now was referring to it, and then after
 *   'while' execution, 'now' points to the newly created node, referred by
 *   the local 'temp' variable.
 * 5. e.g.: start -> [10|add1] at add0 -> [20|add2] at add1 -> [30|NULL] at add2;
 *   'now' points to this add2 having info 30, and '' is NULL,
 *   so that when another node is created, '' refers to the new
 *   node, and then 'now' refers to the new node, and so on.
 * Displaying the list:
 * We start from the starting node, and display 'info' part of each node, and
 * move on to next node by checking the current node's 'next' part is not null.

// This is the Linked List node
class LinkedList{
 int info;   //has value
 LinkedList next; //for pointing to next node

// Demonstration on creation of node and displaying the values
public class LinkedListDemo {

 static LinkedList start = null;
 static LinkedList now = null;
 public static void main(String[] args) {
 static void createNode(int val){
  LinkedList temp = new LinkedList(); = val;
  if (start==null){
   start = temp;
   now = temp;
   now = temp;
 static void display(){
  LinkedList temp = start;
   System.out.print( + "|");
   temp =;

The output will be:
This was a demo program for my understanding, and now I understand how the nodes are connected, and so the term "linked list".

No comments:

Post a Comment

Liked or hated the post? Leave your words of wisdom! Thank you :)