Thursday, August 23, 2018

Reverse a doubly linked list

You’re given the pointer to the head node of a doubly linked list. Reverse the order of the nodes in the list. The head node might be NULL to indicate that the list is empty. Change the next and prev pointers of all the nodes so that the direction of the list is reversed. Return a reference to the head node of the reversed list.
Function Description
Complete the reverse function in the editor below. It should return a reference to the head of your reversed list.
reverse has the following parameter(s):
  • head: a reference to the head of a DoublyLinkedList
Input Format
The first line contains an integer , the number of test cases.
Each test case is of the following format:
  • The first line contains an integer , the number of elements in the linked list.
  • The next  lines contain an integer each denoting an element of the linked list.
Constraints
Output Format
Return a reference to the head of your reversed list. The provided code will print the reverse array as a one line of space-separated integers for each test case.
Solution :-
   static DoublyLinkedListNode reverse(DoublyLinkedListNode head) {
 if (head == null)
                return head;
            var temp = head.next;
            head.next = head.prev;
            head.prev = temp;
            if (head.prev == null)
                return head;
            return reverse(head.prev);
    }




No comments:

Post a Comment

Kafka setup in window

Here's a step-by-step guide on how to do it : 1. Prerequisites : Before you begin, make sure you have the following prerequisites inst...