0

So I have an abstract data type of a singly linked list, and my compiler is stuck when running this part of the test code.

    test.removeDuplicates();
    System.out.println("removeDuplicates() has been run, check following output for counts of 3");
    test.print();

My method for removing duplicates from the given list is as below

public void removeDuplicates() 
{
    if (head == null) return;

    Node iter = head;

    while (iter != null) 
    {
        Node currNode = iter;
        while(currNode  != null && currNode.next != null)
        {
                if(iter.value == currNode.next.value)
                {
                    currNode.next = currNode.next.next;
                    nItem--;
                }
        currNode = currNode.next;
        }
    }
}

I thought this while while loop was looping through the whole list and taking duplicate values out by making pointers skip values to remove them.

apparently one of the while loops does not terminate, it seems my last value isn't getting a pointer to null, but I do not understand why.

AstroCB
  • 12,337
  • 20
  • 57
  • 73
user1702633
  • 111
  • 3
  • 5
  • 8
  • 1
    See also [*How to delete duplicate elements in a list efficiently*](http://stackoverflow.com/q/1801459/230513). – trashgod Sep 28 '12 at 00:41

1 Answers1

3

You are not updating iter on the outer while loop, so it will never be null causing the outer loop to run infinitely.

Add this line just before the end of the outer while loop

iter = iter.next

srikanta
  • 2,914
  • 3
  • 21
  • 35
  • I see that you have not accepted any answers to all your questions. You should start voting and accepting answers. – srikanta Sep 28 '12 at 02:18