Linked List Inserting strings in alphabetical order

Posted by user69514 on Stack Overflow See other posts from Stack Overflow or by user69514
Published on 2010-04-24T16:33:19Z Indexed on 2010/04/24 16:53 UTC
Read the original article Hit count: 163

I have a linked list where each node contains a string and a count. my insert method needs to inset a new node in alphabetical order based on the string. if there is a node with the same string, then i increment the count. the problem is that my method is not inserting in alphabetical order

public Node findIsertionPoint(Node head, Node node){
    if( head == null)
        return null;

    Node curr = head;
    while( curr != null){
        if( curr.getValue().compareTo(node.getValue()) == 0)
            return curr;
        else if( curr.getNext() == null || curr.getNext().getValue().compareTo(node.getValue()) > 0)
            return curr;
        else
            curr = curr.getNext();
    }

    return null;
}

public void insert(Node node){
    Node newNode = node;
    Node insertPoint = this.findIsertionPoint(this.head, node);
    if( insertPoint == null)
        this.head = newNode;
    else{
        if( insertPoint.getValue().compareTo(node.getValue()) == 0)
            insertPoint.getItem().incrementCount();
        else{
            newNode.setNext(insertPoint.getNext());
            insertPoint.setNext(newNode);
        }
    }
    count++;
}

© Stack Overflow or respective owner

Related posts about java

Related posts about linked-list