Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linked list in java

Tags:

java

list

i have to write a very easy 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 items are equal (compared using equals()), it removes duplicate nodes so that only one consecutive copy remains. Hence, no two consecutive items in this list are equal upon completion of the procedure.

After squish() executes, the list may well be shorter than when squish() began. No extra items are added to make up for those removed.

For example, if the input list is [ 0 0 0 0 1 1 0 0 0 3 3 3 1 1 0 ], the output 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 main to execute the 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 can see that the method work fine..only at the end of the list he trhows a null exception pointer. Can you help me? thanks

like image 981
Giu_ai Avatar asked Dec 26 '22 00:12

Giu_ai


1 Answers

The problem is in this line:

while(current.item.equals(current.next.item) && current.next !=null)

Here, the first part of the condition accesses current.next.item, even if current.next is null, since the second part of the condition (current.next !=null) is checked after the first (and only if the first evaluates to true, see below). To fix it, just reverse the condition:

while(current.next !=null && current.item.equals(current.next.item))

This way, the expression current.item.equals(current.next.item) will only be executed if current.next !=null is true (short-circuit evaluation), i.e., when it's safe to do so.

Also, I think you can drop that first if statement. Take a look at @Pete's answer for how to simplify the method.

like image 88
tobias_k Avatar answered Jan 31 '23 13:01

tobias_k