Last active
January 4, 2016 14:29
-
-
Save yekmer/8634508 to your computer and use it in GitHub Desktop.
//solution for http://www.geeksforgeeks.org/pairwise-swap-elements-of-a-given-linked-list-by-changing-links/
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
class SwapLinkedList { | |
static SwapLinkedList sll = new SwapLinkedList(); | |
public static void main(String[] args) { | |
// 1->2->3->4->5->6 | |
Node node6 = sll.new Node(null, 6); | |
Node node5 = sll.new Node(node6, 5); | |
Node node4 = sll.new Node(node5, 4); | |
Node node3 = sll.new Node(node4, 3); | |
Node node2 = sll.new Node(node3, 2); | |
Node root = sll.new Node(node2, 1); | |
if(root != null) { | |
root = swapValues(root); | |
} | |
Node node = root; | |
while(node != null) { | |
System.out.print(node); | |
node = node.next; | |
} | |
} | |
public static Node swapValues(Node node) { | |
if(node == null || node.next == null) return node; | |
Node nextNode = node.next; | |
node.next = nextNode.next; | |
nextNode.next = node; | |
node.next = swapValues(node.next); | |
return nextNode; | |
} | |
class Node { | |
Node next; | |
int value; | |
public Node(Node next, int value) { | |
this.next = next; | |
this.value = value; | |
} | |
@Override | |
public String toString() { | |
return value + "->"; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment