I need to write a very simple method for a linked list class, but I am having some problems. This method, called squish() , takes this list and, wherever two or more consecutive elements are equal (compared using equals() ), it removes duplicate nodes so that only one consecutive copy remains. Therefore, after the completion of the procedure, no two consecutive elements in this list are equal.
After squish() executed, the list may be shorter than when squish() run. No additional items are added to compensate for their removal.
For example, if the input list is [ 0 0 0 0 1 1 0 0 0 3 3 3 1 1 0 ] , then the result list is [ 0 1 0 3 1 0 ] .
This is my method:
public void squish() { SListNode current = head; boolean end =false; while(end == false ) { if(!current.item.equals(current.next.item)) current=current.next; else { while(current.item.equals(current.next.item) && current.next !=null) current.next=current.next.next; current=current.next; } if (current==null) end=true; } }
and this is a small basic task for executing code.
public class main { public static void main(String args[]) { int[] test6 = {6, 6, 6, 6, 6, 3, 6, 3, 6, 3, 3, 3, 3, 3, 3}; SList list6 = new SList(); for (int i = 0; i < test6.length; i++) { list6.insertEnd(new Integer(test6[i])); } System.out.println("squishing " + list6.toString() + ":"); list6.squish(); String result = list6.toString(); System.out.println(result); int[] test5 = {3, 7, 7, 7, 4, 5, 5, 2, 0, 8, 8, 8, 8, 5}; SList list5 = new SList(); for (int i = 0; i < test5.length; i++) { list5.insertEnd(new Integer(test5[i])); } System.out.println("squishing " + list5.toString() + ":"); list5.squish(); result = list5.toString(); System.out.println(result); } }
Debugging the code, I see that the method works fine ... only at the end of the list does it display a pointer to a null exception. Could you help me? thanks