roughosing
roughosing

Reputation: 71

Code storing wrong data in nodes, when previous test's worked right in my Doubly-Linked-List, and giving me an OutOfMemoryError

So I've begun work on this weeks assignment and began with the most important method to implement, the insertbefore() method. This method seems to be working well for each test until the test for insertion at point 2 in the Doubly Linked list. The previous test(insertion at point 1) works well and gives me the expected output but for this test it gives me a wrong output as well as causing an OutOfMemoryError...

I'm quite confused at how this is happening, and why the code is acting unexpectedly. I'm also a bit iffy on the aspect of DoublyLinkedLists, and have been struggling at this program for quite some time, any help at all would be greatly appreciated

Below is my code:

public void insertBefore( int pos, T data ) 
{
    if(isEmpty()){
      DLLNode current = new DLLNode(data,null,null);
      head = current;
      tail = current;
    }
    else if(pos<=0){
      DLLNode current = new DLLNode(data,null,head);
      head.prev = current;
      current.next = head;
      current.prev = null;
      head = current;
    }
    else if(pos>=count){
      DLLNode current = new DLLNode(data,tail,null);
      tail.next = current;
      current.prev = tail;
      current.next = null;
      tail = current;
  }  
    else{
        DLLNode current = new DLLNode(data,null,null);
        int i=1;
        DLLNode posZero = head;
        while(i<count){
            if(i==pos){
                DLLNode tmp = head.next;
                posZero.next = current;
                current.prev = head;
                current.next = tmp;
                tmp.prev = current;                     
            }
            posZero = posZero.next;
            i++;
        }
    }
    System.out.println();
    displayNodeList();
    count++;
  return;
}

Upvotes: 1

Views: 63

Answers (1)

Florian Schaetz
Florian Schaetz

Reputation: 10652

Have a look at this code...

    DLLNode posZero = head;
    while(i<count){
        if(i==pos){
            DLLNode tmp = head.next;

The "tmp" will always be the next of the head, in other words, the 2nd element. This way, you create an endless loop in your toString, since the inserted element points to the 2nd element as next, which then will again point at the inserted, etc.etc.

Head -> 1. -> 2. -> 1. -> 2. -> 1. -> 2. -> etc.

This is why you get an out of memory error: You StringBuilder simply grows and grows and grows... until no memory is left. Fortunately for you, you didn't use recursion for that, since that would have gotten you an StackOverflow... Ok, probably not really better ;-)

And as a suggestion: Your tests would be more readable if you a) put every test in a seperate method and b) used some kind of assertion framework like Hamcrest, AssertJ or Truth.

Upvotes: 2

Related Questions