remove duplicates

package interviewPractice;

import java.util.Hashtable;
import java.util.Iterator;
import java.util.LinkedList;

public class RemoveDupsFromLinklist {

    // using tempory buffer
    public static void deleteDups(LinkedList<String> linkedList) {
        if (linkedList == null) {
            return;
        }
        if (linkedList.size() == 1) {
            return;
        }
        Iterator<String> it = linkedList.iterator();
        Hashtable<String, String> ht = new Hashtable<String, String>();
        while (it.hasNext()) {
            String val = it.next();
            if (Boolean.valueOf(ht.containsKey(val))) {
                it.remove();
            } else {
                ht.put(val, "true");
            }
        }
        /*for( String s : linkedList )
        {
            if( Boolean.valueOf(ht.containsKey( s )) )
            {
                linkedList.remove( s );
                break;
            }
            else
            {
                ht.put( s, "true" );
            }
        }*/
    }

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        LinkedList<String> linkedList = new LinkedList<String>();
        linkedList.add("a");
        linkedList.add("a");
        linkedList.add("b");
        linkedList.add("a");
        linkedList.add("b");
        linkedList.add("c");
        linkedList.add("c");
        linkedList.add("a");
        System.out.println( linkedList );
        deleteDups( linkedList );
        System.out.println( linkedList );
    }

}

Advertisements
This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s