Created
February 24, 2016 00:41
-
-
Save thmain/7ec03d0c4e2f807bc95f to your computer and use it in GitHub Desktop.
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
public class AternateSplit { | |
public static Node head = null; | |
public static Node headA = null; //linked List 1 | |
public static Node headB = null; // Linked List 2 | |
public void Altersplit() { | |
Node currNode = head; | |
if (currNode == null || currNode.next == null) { | |
return; // we have nothing to split, return | |
} | |
headA = currNode; //set the head for first Linked List | |
headB = currNode.next; //set the head for second Linked List | |
while (currNode != null && currNode.next != null) { | |
Node t = currNode.next; | |
currNode.next = t.next; // set the next node for first linked list | |
// Now check if next node is available for second Linked List | |
if (currNode.next != null && currNode.next.next != null) { | |
t.next = currNode.next.next; // set the next node for second linked list | |
} else { // we have reached to the end | |
t.next = null; | |
return; | |
} | |
currNode = currNode.next; // keep moving forward | |
} | |
} | |
public void print(Node x) { | |
System.out.println(""); | |
Node curr = x; | |
while (curr != null) { | |
System.out.print("->" + curr.data); | |
curr = curr.next; | |
} | |
} | |
public static void main(String[] args) throws java.lang.Exception { | |
head = new Node(1); | |
head.next = new Node(2); | |
head.next.next = new Node(1); | |
head.next.next.next = new Node(2); | |
head.next.next.next.next = new Node(1); | |
head.next.next.next.next.next = new Node(2); | |
AternateSplit i = new AternateSplit(); | |
i.print(head); | |
i.Altersplit(); | |
i.print(headA); | |
i.print(headB); | |
} | |
} | |
class Node { | |
int data; | |
Node next; | |
public Node(int data) { | |
this.data = data; | |
next = null; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment