java - Removing "custom" duplicates from a LinkedList -
i have linkedlist collection populated , each node contains id, name, age. want delete nodes have same name , age in linkedlist if id different. example, if list has
111, joe, 21 222, bob, 20 333, bob, 20 //duplicate, should deleted 444, bob, 40
i delete 2nd "bob" because considered duplicate in program, not delete 3rd "bob" because has different age. did googling , people put linkedlist set (since can't have duplicates) put linkedlist, wouldn't work case since id different.
alternatively this, order list name , age using comparable, if name , age it's same between , i-1 index can remove node.
public static class node implements comparable<node>{ int id; string name; int age; //order name public int compareto( node o ){ if(name.equals(o.name)){ return age - o.age; } return name.compareto(o.name); } } public static void main(string []args){ linkedlist<node> list = new linkedlist<node>(); //insert data... collections.sort(list); int = 1; while(i < list.size()){ node = list.get(i-1); node b = list.get(i); if( a.name.equals(b.name) && a.age == b.age ){ list.remove(i); }else{ i++; } } }
}
Comments
Post a Comment