Home > Enterprise >  The tail is replaced instead of append
The tail is replaced instead of append

Time:01-30

I have a method called public void insertAfterSecondOccurrence(T e1, T e2) that would insert an integer after the second occurrence of another integer. However my problem is that if the integer inserted is before the last integer in the list, the method would just replace the tail with the inserted integer instead of appending it.

Here is the method code :

public void insertAfterSecondOccurrence(T e1, T e2) {   
    // insert e1 after the second occurence of e2

    if(isEmpty()) {
        System.out.println("Error the list is empty.");
    }

    SLLNode<T> p = head;
    int count = 0;

    for(int i = 0; i < size(); i  ) {
        if(p.info.equals(e2)) {
            count  ;
        }
        p = p.next;
    }

    if(count <= 1) {
        System.out.println("Error there is no sec");
    }

    SLLNode<T> p2 = head;
    SLLNode<T> p3 = head;
    SLLNode<T> pred =head;
    SLLNode<T> tmp = new SLLNode<T>(e1);
    int count2 = 0;

    for(int i = 0; i < size(); i  ) {
        if(p2.info.equals(e2)) {
            pred = p2.next;
            p3 = p2;
            count2  ;
        }
        if(count2 == 2) {
            break;
        }
        p2 = p2.next;
    }

    pred.next = pred;
    pred = pred.next;
    p3.next = tmp;
}

I tried replacing the last 3 lines with :

tail.next = tail;
tail = tail.next;
p3.next = tmp; 

But it didn't work. Here is an example of how it should be, this is the original array [ 7 5 3 50 7 9 ], after calling the method it should be [ 7 5 3 50 7 30 9 ], what i keep getting is [ 7 5 3 50 7 30 ].

I would appreciate if you give me basic responses this is my first time using the website so I'm not familiar with the terms/slang in this website.

CodePudding user response:

The issue is with the line "pred.next = pred;". This line is making the link from the predecessor node to itself, creating a loop in the linked list and breaking the original linked list structure.

To fix it, change the line to "pred.next = tmp;".

This will link the predecessor node to the newly created node containing element "e1".

Hope this helps.

CodePudding user response:

I have changed the last 3 lines with this code : p3.next = tmp; tmp.next = pred;

And solved my problem.

  • Related