20. Reverse a Doubly linked list

20. Reverse a Doubly linked list


Problem link :- click here


package Linked_List;

public class LinkedList__20
{

	static void reverseDoublyLnkedList(DoublyLinkedList list)
	{
		Node2 cur = list.head;
		Node2 prev = cur;
		for(cur=list.head; cur!=null; cur=cur.prev)
		{
			Node2 temp = cur.next;
			cur.next = cur.prev;
			cur.prev = temp;
			
			prev = cur;
		}
		list.head = prev;
	}
	
	public static void main(String[] args)
	{
		DoublyLinkedList list = new DoublyLinkedList();
		list.push(3);
		list.push(4);
		list.push(5);
		list.push(6);
		
		System.out.println("Linked list before reversing : ");
		list.print();
		
		reverseDoublyLnkedList(list);
		System.out.println("Linked list after reversing : ");
		list.print();
	}

}

Time complexity :- O(n)
Space complexity :- O(1)

Comments

Popular posts from this blog

4.Sort an array of 0's, 1's & 2's.

1. Reverse

3. Height of Binary tree