Skip to content

2.2 Simple LinkedList

Farrukh Ahmad edited this page Dec 15, 2015 · 1 revision

Lets create a very simple LinkedList implementation in java with following operations

  1. Create Linked List
  2. View Items
  3. Get the current Size of the list

Creating Node Class

class Node
{
int data;
Node next;
public Node()
{
    this.next = null;
}
public Node(int data)
{
    this.data = data;
    this.next = null;
}
public Node(int data, Node next) {
    this.data = data;
    this.next = next;
}
public int getData() {
    return data;
}
public void setData(int data) {
    this.data = data;
}
public Node getNext() {
    return next;
}
public void setNext(Node next) {
    this.next = next;
}
}

Create the LinkedList Class:

class LinkedList
{
Node head;
int size;

public LinkedList() {
    head = new Node();
    this.size = 0;
}

public void add(int data)
{
    Node newNode = new Node(data);
    Node currentNode = head;
    while(currentNode.getNext()!=null)
    {
       currentNode =currentNode.getNext();
    }
    currentNode.setNext(newNode);
    size++;
}

 public int getSize() {
    return size;
}

public void setSize(int size) {
    this.size = size;
}


@Override
public String toString()
{
    if(this.size == 0) return "[ ]";
    if(this.size == 1) return "["+head.getNext().getData()+"]";
    
    StringBuilder string = new StringBuilder();
    string.append("[");
    
    Node currentNode = head;
    while(currentNode.getNext()!=null)
    {
        currentNode = currentNode.getNext();
        if(currentNode.getNext()!= null)
            string.append(currentNode.getData()).append(",");
        else
            string.append(currentNode.getData());
                
    }
    string.append("]");
    return string.toString();
}
}

Test Class:

public class SimpleLinkedList
{
public static void main(String args[])
{
    LinkedList linkedList = new LinkedList();
    linkedList.add(10);
    linkedList.add(20);
    linkedList.add(20);
    System.out.println(linkedList);
    System.out.println(linkedList.getSize());
    
}
}

Clone this wiki locally