How to do insert method on Word Frequency counter using linked list

758 views Asked by At
public class Frequency<E extends Comparable> implements Iterable<E>{
    private Node first;
    private int N;
    Frequency(){
        N = 0;
        first = null;
    }

    @Override
    public Iterator<E> iterator() {
        return new ListIterator();
    }
    /**
     * 
     * List iterator
     *
     */
    private class ListIterator implements Iterator<E>{
        private Node current;
        private int index ;
        ListIterator(){
            current = first;
            index = 0;
        }

        @Override
        public boolean hasNext() {
            return current != null;
        }


        public E next() {
            if(!hasNext()){
                return null;
            }
            E word = current.key;
            int count = current.count;
            String r = "("+word + "," + Integer.toString(count)+")";
            current = current.next;
            return (E)r;
        }

        @Override
        public void remove() {

        } 
        public int compareTo(Frequency<E>.Node first) {
                return next.compareTo(first);
        }
    }
    }
    /**
     * 
     * Node class
     *
     */
    private class Node {
        private E key;
        private int count;
        private Node next;
        Node(E item){
            key = item;
            count = 1;
            next = null;
        }
        @Override 
        public String toString(){
            return "("+key +","+count+")";
        }
    }
    /*
     * Inserts a word into the linked list. If the word exists, increment the 
     * count by 1. 
     */
    public void insert(E word){
        if(word.equals("")){
            return;
        }
        Node current=first;
    Node temp=null;
    while(current != null){
        if(current.key.equals(word)){
            current.count++;
            temp=current;
        }
        current=current.next;   
    }
    while(temp !=null && temp.next != null){
        if(temp.count>first.count){
            temp=first.next;
            first.next=temp.next;
            temp.next=first;
            first=temp;
        }
    }
    while(temp !=null && temp.next != null){
        if(temp.count==first.count){
            if(temp.compareTo(first)<0){
                temp=first.next;
                first.next=temp.next;
                temp.next=first;
                first=temp;     
            }
        }
    }
}

I need to sort the words in their frequency order from most frequent word to the least frequent. If two words have the same frequency they are sorted in alphabetical order. I'm not sure how to do the insert method that combines all the things I have to do. I've made attempts to do the add count part and the frequency ordering part, and I have no idea how to sort the same frequencies alphabetically. Any help would be appreciated.

0

There are 0 answers