Fam fas
Fam fas

Reputation: 37

Bug while Swapping a LinkedList

Here I am trying to Swap the Head and tail of a singly Linked list

 public void reversePI() {
        Node N1 = this.tail;
        Node Helper = this.head.next;
        this.tail = this.head;
        this.tail.next = null;
        this.head = N1;
        this.head.next = Helper;
        this.display();
    }

Here is the further Approach for the above function to explain my way of thinking. Let us assume we have a Link list as

4k(adress) 1(data)-->5k(adress) 2(data)-->6k(adress) 3(data)-->7k(adress) 4(data)-->null

we have a code

now when the first line executes

N1= 7k(adress) 4(data)

Helper=5k(adress) 2(data)

this.tail=4k(adress) 1(data)

at this point the list should be

  5k(adress) 2(data)-->6k(adress) 3(data)-->4k(adress) 1(data)-->5k(adress) 2(data)

now we set the tail as null to break the initial link

this.tail.next = null;

5k(adress) 2(data)-->6k(adress) 3(data)-->4k(adress) 1(data)-->null

now this.head = N1;

7k(adress) 4(data)  5k(adress) 2(data)-->6k(adress) 3(data)-->4k(adress) 1(data)-->null

after this this.head.next = Helper; line will establish the link and

7k(adress) 4(data)--> 5k(adress) 2(data)-->6k(adress) 3(data)-->4k(adress) 1(data)-->null

is my Approch correct or is there something I am missing that leads to generating an infinite output while running the display method -->

public void display() {
            Node current = this.head;
            while (current != null) {
                System.out.print(current.data + " ");
                current = current.next;
            }
        }

Upvotes: 0

Views: 37

Answers (1)

weilueluo
weilueluo

Reputation: 683

You forgot to handle the second last node's next, it should point to the new tail, but it is still pointing to the old tail which is the new head. This results in a loop: head -> ... -> secondLastNode -> head

Upvotes: 2

Related Questions