We use cookies to give you the best experience on our website. If you continue to browse, then you agree to our privacy policy and cookie policy. Image for the cookie policy date

Java Help: Reversing a Linked List

Hello all, I'm trying to reverse a linked list using Java and am having a bit of trouble. I'm getting an error and the list isn't reversing properly. I've included my code below. Any help would be greatly appreciated.

public static void reverseList(Node node) { Node prev = null; Node current = node; Node next = null; while (current != null) { next = current.next; current.next = prev; prev = current; current = next; } node = prev; }

Thanks for your help!


1 Reply

RR Rajendran R Syncfusion Team May 8, 2023 03:58 AM UTC

Hi Customer,


We understand that your query seems general without any Syncfusion components. To achieve your requirements without any issue, follow this requirement.


  1. Create Node class to represent linked list.


class Node {

    int value;

    Node next;

 

    public Node(int value) {

        this.value = value;

        this.next = null;

    }

}


  1. Create the linked list class that process the node.

class LinkedList {

    Node head;

 

    public void reverse() {

        Node previous = null;

        Node current = head;

        Node next = null;

 

        while (current != null) {

            next = current.next;

            current.next = previous;

            previous = current;

            current = next;

        }

 

        head = previous;

    }

 

    public void insert(int value) {

        Node newNode = new Node(value);

        if (head == null) {

            head = newNode;

        } else {

            Node current = head;

            while (current.next != null) {

                current = current.next;

            }

            current.next = newNode;

        }

    }

 

    public void display() {

        Node current = head;

        while (current != null) {

            System.out.print(current.value + " ");

            current = current.next;

        }

        System.out.println();

    }

}


  1. Now, populate the list and reverse it.


public class Main {

    public static void main(String[] args) {

        LinkedList linkedList = new LinkedList();

        linkedList.insert(1);

        linkedList.insert(2);

        linkedList.insert(3);

        linkedList.insert(4);

        linkedList.insert(5);

 

        System.out.println("Original list:");

        linkedList.display();

 

        System.out.println("Reversed list:");

        linkedList.reverse();

        linkedList.display();

    }

}


We ensured that the above code would work properly while execute it. Could you please share any requirements while integrating our Syncfusion components?


Regards,

Rajendran R.


Loader.
Live Chat Icon For mobile
Up arrow icon