Invert List

Node for List

Node.java

public class Node { 
 
    int data; 
    Node next = null; 
 
    public Node(int d) { 
        data = d; 
    } 
 
    void appendToTail(int d) { 
        System.out.println("Adding " + d + "..."); 
        Node n = this; 
        while (n.next != null) { 
            n = n.next; 
        } 
        n.next = new Node(d); 
        this.printList(); 
    } 
 
    Node removeNode(int d) { 
        System.out.println("Removing " + d + "..."); 
        Node n = this; 
        if (n.data == d) { 
            this.printList(); 
            return this.next; 
        } 
        while (n.next != null) { 
            if (n.next.data == d) { 
                n.next = n.next.next; 
                this.printList(); 
                return this; 
            } 
            n = n.next; 
        } 
        this.printList(); 
        return null; 
    } 
 
    void printList() { 
        Node n = this; 
        while (n.next != null) { 
            System.out.print(n.data + " "); 
            n = n.next; 
        } 
        System.out.print(n.data); 
        System.out.println(); 
        System.out.println(); 
    } 
 
}

Invert List


public class InvertList { 
 
    public static void main(String[] args) { 
 
        System.out.println("Initializing Node with " + 1); 
        Node list = new Node(1); 
        list.printList(); 
 
        list.appendToTail(2); 
        list.appendToTail(3); 
        list.appendToTail(4); 
        list.appendToTail(5); 
 
        Node prev = null; 
        Node current = list.next; 
 
        list.next = prev; 
        while (current != null) { 
            prev = list; 
            list = current; 
            current = list.next; 
            list.next = prev; 
        } 
 
        System.out.println("Inverted List"); 
        list.printList(); 
 
    } 
}