2020年5月16日 星期六

Leetcode題解 Python & C#:五月挑戰DAY16 Odd Even Linked List

給一個 linked list,要以 偶數位 奇數位 重新排列。

要求在 O(1) Space、 O(n) Time 解決。

分別拆成偶數奇數頭出來,再把剩下的 linked list 分給兩者,最後合併,回傳偶數頭。這符合題目要求。

或者直接在頭尾開始接,但這預期不如上者,因為上者到 n-1 位置時,就幾乎要完成了;而這方法才剛開始。

Python
class Solution:
    def oddEvenList(self, head: ListNode) -> ListNode:
        if not head or not head.next: return head
        oddHead = OP = head
        evenHead = EP = head.next
        #
        head = head.next.next
        i = 0
        while head:
            i += 1            
            if i % 2 == 1:
                OP.next = head
                OP = OP.next
            else:
                EP.next = head
                EP = EP.next 
            head = head.next
        EP.next = None 
        OP.next = evenHead
        return oddHead
C#
public class Solution {
    public ListNode OddEvenList(ListNode head) {
        if(head is null){return head;}
        if(head.next is null){return head;}
        ListNode OddHead = head; ListNode OddLN = OddHead;
        ListNode EvenHead = OddHead.next; ListNode EvenLN = EvenHead;
        head = head.next.next;
        int i = 0;
        while(!(head is null))
        {
            if(i % 2 == 0)
            {
                OddLN.next = head;
                OddLN = OddLN.next;
            }
            else
            {
                EvenLN.next = head;
                EvenLN = EvenLN.next;
            }
            i += 1;
            head = head.next;
        }
        EvenLN.next = null;
        OddLN.next = EvenHead;
        return OddHead;
    }
}