[LeetCode] Odd Even Linked List 奇偶鏈表


 

Given a singly linked list, group all odd nodes together followed by the even nodes. Please note here we are talking about the node number and not the value in the nodes.

You should try to do it in place. The program should run in O(1) space complexity and O(nodes) time complexity.

 

Example:
Given 1->2->3->4->5->NULL,
return 1->3->5->2->4->NULL.

Note:
The relative order inside both the even and odd groups should remain as it was in the input. 
The first node is considered odd, the second node even and so on ...

Credits:
Special thanks to @aadarshjajodia for adding this problem and creating all test cases.

 

這道題給了我們一個鏈表,讓我們分開奇偶節點,所有奇節點在前,偶節點在后。我們可以使用兩個指針來做,pre指向奇節點,cur指向偶節點,然后把偶節點cur后面的那個奇節點提前到pre的后面,然后pre和cur各自前進一步,此時cur又指向偶節點,pre指向當前奇節點的末尾,以此類推直至把所有的偶節點都提前了即可,參見代碼如下:

 

解法一:

class Solution {
public:
    ListNode* oddEvenList(ListNode* head) {
        if (!head || !head->next) return head;
        ListNode *pre = head, *cur = head->next;
        while (cur && cur->next) {
            ListNode *tmp = pre->next;
            pre->next = cur->next;
            cur->next = cur->next->next;
            pre->next->next = tmp;
            cur = cur->next;
            pre = pre->next;
        }
        return head;
    }
};

 

還有一種解法,用兩個奇偶指針分別指向奇偶節點的起始位置,另外需要一個單獨的指針even_head來保存偶節點的起點位置,然后把奇節點的指向偶節點的下一個(一定是奇節點),此奇節點后移一步,再把偶節點指向下一個奇節點的下一個(一定是偶節點),此偶節點后移一步,以此類推直至末尾,此時把分開的偶節點的鏈表連在奇節點的鏈表后即可,參見代碼如下;

 

解法二:

class Solution {
public:
    ListNode* oddEvenList(ListNode* head) {
        if (!head || !head->next) return head;
        ListNode *odd = head, *even = head->next, *even_head = even;
        while (even && even->next) {
            odd = odd->next = even->next;
            even = even->next = odd->next;
        }
        odd->next = even_head;
        return head;
    }
};

 

LeetCode All in One 題目講解匯總(持續更新中...)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM