Wednesday, October 26, 2011

Simple LinkedList implementation in java without iterator

package org.learn.collections.list.linkedlist;

/* a linked list is a data structure consisting of a group of nodes which together represent a sequence.
 * Under the simplest form, each node is composed of a datum and a reference (in other words, a link)
 * to the next node in the sequence; more complex variants add additional links.
 * This structure allows for efficient insertion or removal of elements from any position in the sequence.
 * But reading a particular node in a list is time consuming action because it has to travel all previous
 * nodes of the target node.
 *
*/

/*
 * This code is working perfectly without any issues. Need to handle the null pointer exceptions only.
 */
public class LinkedList {

    Node header;

    public LinkedList(int data) {
        header = new Node(data);
    }

    public void insert(Node n) {

        if (header == null) {
            header = n;
        } else {
            Node node = header;
            while (node.next != null) {
                node = node.next;
            }

            node.next = n;

        }
    }

    public void insertAt(int pos, Node newNode) {

        Node temp = null;
        if (pos == 1) {
            newNode.next = header;
            header = newNode;
        } else if (pos > 1) {
            Node node = header;
            for (int x = 2; x < pos; x++) {
                if (node != null)
                    node = node.next;
            }
            temp = node.next;
            node.next = newNode;
            newNode.next = temp;
        }
    }

    public void printLinkedList() {
        Node node1 = header;
        while (node1 != null) {
            System.out.print(node1.data);
            node1 = node1.next;
            if (node1 != null)
                System.out.print("->");
        }
    }

    public static void main(String[] args) {
        LinkedList ll = new LinkedList(10);
        ll.insert(new Node(12));
        ll.insert(new Node(13));
        ll.insert(new Node(14));
        ll.insertAt(2, new Node(11));
        ll.insertAt(1, new Node(5));
        ll.insertAt(7, new Node(59));
        ll.insertAt(5, new Node(59));
        ll.printLinkedList();
    }

}

class Node {
    int data;
    Node next;
   
    public Node(int data,Node node){
        this.data=data;
        this.next= node;
    }
    public Node(int data){
        this(data,null);
    }
}

No comments:

Post a Comment