328. Odd Even Linked List

最后更新

二刷。。至少是二刷。。

感觉linked list的题可操作性都比较小,基本都是楞做,难在edge cases上,一般通过dummy这种可以解决烦恼。。

这个题就俩HEAD代表ODD和EVEN就行了。。

最后别忘了odd的尾连着even的头,even的尾指向NULL。

否则就成环了,这个题目的是要做人体蜈蚣,不是环。

public class Solution {
    public ListNode oddEvenList(ListNode head) {
        if (head == null || head.next == null || head.next.next == null) return head;
        ListNode temp1 = head;
        ListNode temp2 = head.next;
        ListNode second = head.next;
        ListNode temp = temp2.next;
        boolean odd = true;
        while (temp != null) {
            if (odd) {
                temp1.next = temp;
                temp1 = temp1.next;
                odd = !odd;
            } else {
                temp2.next = temp;
                temp2 = temp2.next;
                odd = !odd;
            }
            temp = temp.next;
        }
        temp1.next = second;
        temp2.next = null;
        return head;
    }
}
原文地址:https://www.cnblogs.com/reboot329/p/6213851.html