Tuesday, June 19, 2018

[2018-Interview] Odd Even Linked List

Original question: https://leetcode.com/problems/odd-even-linked-list/description/

My answer:



/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode oddEvenList(ListNode head) {
        if (head == null || head.next == null || head.next.next == null ) {
            return head;
        }
        ListNode evenHead = head.next;

        ListNode currentOdd = head;
        ListNode currentEven = head.next;
        while (currentOdd != null && currentEven != null && currentEven.next != null) {
            currentOdd.next = currentEven.next;
            currentEven.next = currentEven.next.next;
            currentOdd = currentOdd.next;
            currentEven = currentEven.next;
        }
        currentOdd.next = evenHead;
        return head;
    }
}


No comments:

Post a Comment