Odd Even Linked List
Input: 1->2->3->4->5->NULL
Output: 1->3->5->2->4->NULLInput: 2->1->3->5->6->4->7->NULL
Output: 2->3->6->7->1->5->4->NULLAnalysis
Input: 1->2->3->4->5->NULLSolution
Last updated
Input: 1->2->3->4->5->NULL
Output: 1->3->5->2->4->NULLInput: 2->1->3->5->6->4->7->NULL
Output: 2->3->6->7->1->5->4->NULLInput: 1->2->3->4->5->NULLLast updated
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode oddEvenList(ListNode head) {
ListNode pOdd = new ListNode(0);
ListNode pEven = new ListNode(0);
ListNode p = head;
ListNode p1 = pOdd;
ListNode p2 = pEven;
if (head == null || head.next == null) {
return head;
}
while (p != null) {
pOdd.next = p;
pOdd = pOdd.next;
if (p.next != null) {
pEven.next = p.next;
pEven = pEven.next;
p = p.next.next;
} else {
pEven.next = null;
break;
}
}
pOdd.next = p2.next;
return p1.next;
}
}public class Solution {
public ListNode oddEvenList(ListNode head) {
if (head != null) {
ListNode odd = head, even = head.next, evenHead = even;
while (even != null && even.next != null) {
odd.next = odd.next.next;
even.next = even.next.next;
odd = odd.next;
even = even.next;
}
odd.next = evenHead;
}
return head;
}
}