Skip to content

Instantly share code, notes, and snippets.

@Frederikos
Created April 2, 2020 12:32
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 Frederikos/6cf122b01d300523d7cfe5c39abbd4ce to your computer and use it in GitHub Desktop.
Save Frederikos/6cf122b01d300523d7cfe5c39abbd4ce to your computer and use it in GitHub Desktop.
class LinkedList {
Node head;
static class Node {
int data;
Node next;
Node(int d)
{
data = d;
next = null;
}
}
//function to reverse but not needed
Node reverse(Node node)
{
Node prev = null;
Node current = node;
Node next = null;
while (current != null) {
next = current.next;
current.next = prev;
prev = current;
current = next;
}
node = prev;
return node;
}
//Push to front so we don't need to call reverse
public void push(int element)
{
Node node = new Node(element);
node.next = head;
head = node;
}
static void printList(Node node)
{
while (node != null) {
System.out.print(node.data + " ");
node = node.next;
}
System.out.println();
}
public static void main(String[] args)
{
Node node = new Node(1);
node.next = new Node(2);
node.next.next = new Node(3);
node.next.next.next = new Node(4);
printList(node);
LinkedList[] results = separateToOddEven(node);
printList(results[0].head);
printList(results[1].head);
}
private static LinkedList[] separateToOddEven(Node node) {
LinkedList oddElements = new LinkedList();
LinkedList evenElements = new LinkedList();
LinkedList[] result = {oddElements, evenElements};
Node current = node;
while (current!=null) {
int item = current.data;
if ((item & 1) == 1) {
oddElements.push(item);
} else {
evenElements.push(item);
}
current = current.next;
}
return result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment