Skip to content

Instantly share code, notes, and snippets.

@InterviewBytes InterviewBytes/ListNode.java Secret
Created Jun 9, 2017

Embed
What would you like to do?
OddEvenList
package com.interviewbytes.linkedlists;
public class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
}
}
package com.interviewbytes.linkedlists;
public class OddEvenList {
public ListNode oddEvenList(ListNode head) {
ListNode oddSentinel = new ListNode(0);
ListNode oddCurrent = oddSentinel;
ListNode evenSentinel = new ListNode(0);
ListNode evenCurrent = evenSentinel;
boolean odd = true;
while (head != null) {
if (odd) {
oddCurrent.next = head;
oddCurrent = oddCurrent.next;
} else {
evenCurrent.next = head;
evenCurrent = evenCurrent.next;
}
head = head.next;
odd = !odd;
}
oddCurrent.next = evenSentinel.next;
evenCurrent.next = null;
return oddSentinel.next;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.