Linked List: Reverse a linked list

Question: Reverse a linked list

package additional_problems.linkedList;

/**
 * Created by aarushi on 5/7/21.
 */
public class P10Reverse {
    public static void reverseLinkedList(LinkedList list){
        ListNode previousNode=null, currentNode= list.head, nextNode;

        while(currentNode!=null){
            //set the next node equal to the current node
            nextNode=currentNode.getNext();
            //set the current node equal to the previous node
            currentNode.setNext(previousNode);
            //set the previous node equal to the current node
            previousNode=currentNode;
            //current node equal to the next node
            currentNode=nextNode;
        }

        //change position of the head
        list.head=previousNode;

    }

    public static void main (String [] args){
//create a linked list
        LinkedList list = new LinkedList();
        ListNode node= new ListNode(19);
        list.add(node);
        node= new ListNode(28);
        list.add(node);
        node= new ListNode(37);
        list.add(node);
        node= new ListNode(46);
        list.add(node);
        node= new ListNode(55);
        list.add(node);
        node= new ListNode(6);
        list.add(node);
        node= new ListNode(7);
        list.add(node);
        node= new ListNode(25);
        list.add(node);
        node= new ListNode(2);
        list.add(node);

        list.printNoException();

        reverseLinkedList(list);

        list.printNoException();
    }
}

Leave a Reply

PHP JS HTML CSS BASH PYTHON CODE

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: