Search code examples
javalinked-listswap

Swap two elements from a linked list given a position


I want to program a function that swaps the element of a list given a position, for example:

original list:
10-->20-->30-->40-->50-->60

and if I give position 3 I would like the resulting list to be:

10-->20-->40-->30-->50-->60

Consider that I do not want to swap the elements, but to swap the nodes. Also, I have implemented a version, but using an auxiliary linked list, which it works, but I am curious about how to solve this only using the links of the list. So far I have the following:

public class Node {
    public int elem;
    public Node next;
    public Nodo(int elem){
        this.elem=elem;
    }
}

public class LinkedList{
    Node first;
    Node front;
    int c;
    public void add(int n){
        Node n=new Node(n);
        if (front==null){
            first=n;
        }
        else{
            front.next=n;
        }
        front=n;
        c++;
    }
 public void print(){
        Node t=first;
        while (t!=null){
            System.out.println(t.e);
            t=t.next;
        }
    }

public void swap(int pos){
            int c=1;
            Node prev=first;
            Node curr=prev.next;
            Node t=null;
            if (curr.next==null) System.out.println("next element is null");
            else{
                while (c<pos){
                    prev=prev.next;
                    curr=curr.next;
                    c++;
                }
                t=curr.next;
                curr.next=prev.next;
                prev.next=t;
            }
        }

public static void main(String[] args) {
        LinkedList l=new LinkedList();
        l.add(10);
        l.add(20);
        l.add(30);
        l.add(40);        
        l.add(50);
        l.add(60);
        l.swap(3);
        l.print();
}

The problem is that when I run my program one of the elements to be swapped disappears. What am I doing wrong?


Solution

  • The issues in your code are: 1) you are keeping track of the wrong prev node; 2) you need to handle the head case as well (pos = 1); 3) you need to also swap the next pointers.

    public void swap(int pos) {
        Node prev = null;
        Node curr = first;
        for(int c = 1; curr != null && c < pos; c++){
                prev = curr;
                curr = curr.next;
        }
        if (pos <= 0 || curr == null || curr.next == null) {
            System.out.println("Next element is null or pos is invalid");
        }
        else if(prev == null){
            Node t = curr.next;
            curr.next = curr.next.next;
            t.next = first;
            first = t;
        }
        else {
            Node t = curr.next;
            curr.next = curr.next.next;
            t.next = prev.next;
            prev.next = t;
        }
    }