Skip to content

Instantly share code, notes, and snippets.

@yekmer
Last active January 4, 2016 14:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yekmer/8634508 to your computer and use it in GitHub Desktop.
Save yekmer/8634508 to your computer and use it in GitHub Desktop.
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