How To Reverse A Node Integer Linked List In Java

How To Reverse A Node Integer Linked List In Java | Let us demonstrate how to reverse a linked list.

public class Main {
    static Node head;

    static class Node {

        int data;
        Node next;

        Node(int d) {
            data = d;
            next = null;
        }
    }

    Node reverseList(Node node) {
        Node previous = null;
        Node current = node;
        Node next = null;
        while (current != null) {
            next = current.next;
            current.next = previous;
            previous = current;
            current = next;
        }
        node = previous;
        return node;
    }

    void printList(Node node) {
        while (node != null) {
            System.out.print(node.data + " ");
            node = node.next;
        }
    }

    public static void main(String[] args) {
        Main list = new Main();
        list.head = new Node(88);
        list.head.next = new Node(55);
        list.head.next.next = new Node(24);
        list.head.next.next.next = new Node(00);

        System.out.println("The Linked list is: ");
        list.printList(head);
        head = list.reverseList(head);
        System.out.println("");
        System.out.println("After Reversing the linked list: ");
        list.printList(head);
    }
}

Output:-

The Linked list is:
88 55 24 0
After Reversing the linked list:
0 24 55 88

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!

Leave a Comment

Your email address will not be published. Required fields are marked *