328. Odd Even Linked List - Medium

前往題目

想法

  • 這題要求把linkedlist,重新排成奇數項node在前,偶數項node在後,同時維持他們的相對順序

思路

  1. oddeven指針分別指著奇數項和偶數項
  2. 藉由觀察可以看到odd的下一項一定是even指針的下一項,而even的下一項一定是even的下下項
  3. 拼接後再移動指針
  4. 最後odd拼上even

WA的code

不難,但是指針操作還是有點問題

class Solution {
    public ListNode oddEvenList(ListNode head) {
        if (head.next == null) return head;


        ListNode dummyEven = new ListNode(0, head.next);

        // Odd and even pointer
        ListNode odd = head, even = head.next;

        ListNode evenNodes = dummyEven;

        while (even != null &&
                even.next != null && 
                even.next.next != null) {
            // Link odd and even "th" node
            odd.next = even.next;
            evenNodes.next = even;
            
            // Move pointers
            odd = even.next;
            even = even.next.next;
            evenNodes.next = evenNodes;
        }

        // Combine
        evenNodes.next = even;

        odd.next = dummyEven.next;

        return head;

    }
}

Code

參考一下討論區解答順利修正

class Solution {
    public ListNode oddEvenList(ListNode head) {
        if (head == null) return head;

        // Odd and even pointer
        ListNode odd = head, even = head.next;
        // Even nodes
        ListNode evenHead = even;

        while (even != null && even.next != null) {
            // Join
            odd.next = even.next;
            even.next = even.next.next;

            // Move pointers
            odd = odd.next;
            even = even.next;
        }

        // Combine
        odd.next = evenHead;

        return head;
    }
}

2024/04/29

  • 寫出來了,雙指針搞定

328. Odd Even Linked List - Medium
https://f88083.github.io/2023/12/19/328-Odd-Even-Linked-List-Medium/
作者
Simon Lai
發布於
2023年12月19日
許可協議