This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Created with IntelliJ IDEA. | |
* User: Ravi | |
* Date: 11/6/13 | |
* Time: 5:45 AM | |
* To change this template use File | Settings | File Templates. | |
*/ | |
public class DoublyLinkedListTest { | |
public static void main(String[] args) | |
{ | |
Node head = null; | |
head = Insert(head, 1); | |
head = Insert(head, 2); | |
head = Insert(head, 3); | |
head = Insert(head, 4); | |
head = Insert(head, 5); | |
Print(head); | |
head = Reverse(head); | |
Print(head); | |
} | |
static class Node | |
{ | |
public int data; | |
public Node prev; | |
public Node next; | |
} | |
public static Node Reverse(Node head) | |
{ | |
//If 0 or 1 node? no need to reverse; trivial case | |
if( head == null || head.next == null ) | |
return head; | |
Node prevNode = null; | |
Node curNode = head; | |
while ( curNode != null ) | |
{ | |
prevNode = curNode.prev; | |
curNode.prev = curNode.next; | |
curNode.next = prevNode; | |
curNode = curNode.prev; | |
} | |
return prevNode.prev; | |
} | |
public static void Print(Node head) | |
{ | |
for( Node ptr = head; ptr != null ; ptr = ptr.next ) | |
{ | |
System.out.print(ptr.data + " "); | |
} | |
System.out.println(); | |
} | |
public static Node Insert(Node head, int data) | |
{ | |
if( head == null ) | |
{ | |
head = new Node(); | |
head.data = data; | |
head.next = null; | |
head.prev = null; | |
return head; | |
} | |
Node newNode = new Node(); | |
newNode.data = data; | |
newNode.next = head; | |
head.prev = newNode; | |
newNode.prev = null; | |
return newNode; | |
} | |
} |