Notice: Function _load_textdomain_just_in_time was called incorrectly. Translation loading for the mission-news domain was triggered too early. This is usually an indicator for some code in the plugin or theme running too early. Translations should be loaded at the init action or later. Please see Debugging in WordPress for more information. (This message was added in version 6.7.0.) in C:\inetpub\wwwroot\blogs\wp-includes\functions.php on line 6121
Reversing a Linked List – Club TechKnowHow! Press "Enter" to skip to content

Reversing a Linked List

If we had to reverse the elements of an array we would have to iterate over then entire array and swap the ith element with the (n-i-1)th element where n is the size of the array.

Now in a linked list we are not required to swap the data in the nodes. Instead we can achieve the same by just reversing the pointers, initializing the head to the last element of the given linked list and point the head of the original linked list to null.

So we will create 2 variables; one of them will always point to the node that the current node needs to point at, and the other will always point to the node the current node is currently pointing at. If we iterate till the current node – starting from head is not ‘null’ then we would have reversed the entire linked list.

 

static void reverse_linked_list(LinkedList l) {
        Node prev = null;
        Node temp = l.head;
        while (l.head != null) {
            temp = l.head.next;
            l.head.next = prev;
            prev = l.head;
            l.head = temp;
        }
        l.head = prev;
}

 

Be First to Comment

Leave a Reply

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