Move last element to front in a linked list

Problem: For any given linked list, move the last element to front

Problem Explanation: For any linked list,

Input: 1 -> 2 ->3 ->4 -> 5

Ouput: 5 -> 1 -> 2 ->3 ->4

 

Input: 9 -> 10 ->11 ->12

Ouput: 12 -> 9 -> 10 ->11

Java Implementation

public class ProcessLL {
    public Node processLL(Node node) {
        Node cur = node, prev = cur;
        while (cur.getLink() != null) {
            prev = cur;
            cur = cur.getLink();
        }

        cur.setLink(node);
        prev.setLink(null);
        return cur;
    }

    public void printLL(Node node) {
        while (node != null) {
            System.out.print(node.getValue());
            node = node.getLink();
        }
    }

    public static void main(String[] args) {
        Node node = new Node(1, null);
        node.setLink(new Node(2, null));
        node.getLink().setLink(new Node(3, null));
        node.getLink().getLink().setLink(new Node(4, null));
        node.getLink().getLink().getLink().setLink(new Node(5, null));

        ProcessLL processLL = new ProcessLL();
        node = processLL.processLL(node);
        processLL.printLL(node);
    }
}

public class Node {
    int value;
    Node link;

    public Node(int value, Node n) {
        this.value = value;
        this.link = n;
    }

    public int getValue() {
        return value;
    }

    public void setValue(int value) {
        this.value = value;
    }

    public Node getLink() {
        return link;
    }

    public void setLink(Node link) {
        this.link = link;
    }
}

TimeComplexity: O(n)


Note: If you find any other better way to approach to this problem or you find any issue/error in above code snippets/approaches – please share it in the comments section below and get a chance to enrol free of cost for an online Live Data Structure and Algorithm course (specially designed for interview preparation for software companies like Amazon, Google, Facebook, FlipKart, SnapDeal, HealthKart…)