Saturday, 2 August 2014

Singly Linked List - java

Base classes for singly linked list - the head and tail are sentinels for the singly linked list  list



Node class
/*
 *  @ Node class to implement a node of a linked list
 *  @data Element the string data of node , Next the reference to the next node object reference
 */
public class Node {
private String element ;
Node next ;

//constructor
//creates a node with given element and reference to the next node
public Node(String s , Node n)
{
this.element = s;
this.next = n;

}

// getters and setters modifiers for this node
public String getElement()
{
return this.element;
}

public Node getNext()
{
return this.next;
}

public void setElement( String newElem )
{
this.element = newElem;
}
public void setNext( Node newNxt )
{
this.next = newNxt;
}

}


Singly Linked List class - 
/*
 *  @ SinglyLinkedList class to implement singly linked list
 */
public class SinglyLinkedList {
//head and tail of list
protected Node head , tail  ;
static int totalNodes ; 
//default constructor creates an empty list
public SinglyLinkedList()
{
this.head = null;
SinglyLinkedList.totalNodes = 0 ;
}
// insertion at the head of a linked list
public void addAtHead(Node newNode)
{
//set the next reference of new node same as head of the linked list
newNode.setNext(head);
//make head to  point the new node making new node to be the first element of the linked list
head = newNode ; 
// increment the number of nodes  
++totalNodes;
}
//insert at the tail of linked list
public void addAtTail(Node newNode)
{
//set the next referencee of new node ass null 
newNode.setNext(null);
//make the last node to point the newNode
tail.setNext(newNode);
// now finally make the tail to point to the newNode
tail = newNode ; 
// increment the total nodes present
++totalNodes;
}
// remove the first element of the list
public void removeFirstNode(){
// store the first node in a  temporary reference to remove it
Node temp = head ; 
// make head to point to the second node 
head =  head.getNext();
// null out the next poiner of the removed node
temp.setNext(null);
//decrement the total nodes present
--totalNodes;
}

}

No comments:

Post a Comment