vendredi 28 avril 2017

Improve Java LinkList implimentation

I am trying to implement linklist data structure in java. Following is my implementation:

// A singly Linked List
class Node{

int value;
Node next;

Node(int n){
    this.value = n;
    this.next = null;
}

public void printNode(){
    System.out.println("Value: " + value);
}

}

class LinkList{

private Node first;
private Node last;

public LinkList(){
    first = null;
    last = null;
}

public boolean isEmpty(){
    return first == null;
}

public void insertFirst(int n){


    Node node = new Node(n);


    if(first == null){
        System.out.println("1. Vlaue of n: "+n);
        first = node;
        last = node;
    }else{
        System.out.println("2. Vlaue of n: "+ n);
        Node tmp = first; 
        first = node;
        node.next = tmp;

    }

}

public void deleteFirst(){
    if (!isEmpty()){
        Node tmp = first; 
        first = tmp.next;
    }
}

public void deleteLast(){

    if(!isEmpty()){

        Node tmp = first;
        Node oneBeforeLast = null;

        while (tmp.next != null){
            oneBeforeLast = tmp;
            tmp = tmp.next;
        }

        oneBeforeLast.next = null;

    }
}

public void deleteNode(int value){

    if (!isEmpty()) {

        Node tmp = first;
        Node oneBeforeLast = first;

        while (tmp.next != null) {

            if (tmp.value == value) {

                if (oneBeforeLast == first) {
                    first = tmp.next;
                } else
                    oneBeforeLast.next = tmp.next;
            }
            oneBeforeLast = tmp;
            tmp = tmp.next;
            System.out.println("Btmp: " + oneBeforeLast.value + " tmp: 
            " + tmp.value);
        }

        if (tmp.next == null && tmp.value == value) {
            oneBeforeLast.next = null;
        }
    }
}

public void printList(){

    Node tmp = first;

    System.out.println("\nPrinting List:");

    while(tmp != null){
        tmp.printNode();
        tmp = tmp.next;
    }
  }
}


public class LinkListTest {



public static void main(String[] args) {
    // TODO Auto-generated method stub
    LinkList linklist = new LinkList();
    linklist.insertFirst(1);
    linklist.insertFirst(2);
    linklist.insertFirst(3);
    //linklist.insertFirst(3);
    linklist.insertFirst(4);

    linklist.printList();

    //linklist.deleteFirst();
    //linklist.printList();

    //linklist.deleteLast();
    //linklist.printList();

    linklist.deleteNode(1);
    linklist.printList();
 }

}

I would like to improve it further and check its efficiency for large inputs. Can anyone give some pointers on these two pointers please?

Aucun commentaire:

Enregistrer un commentaire