1. 程式人生 > >[LeetCode] Odd Even Linked List 奇偶連結串列

[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;
    }
};