[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.html

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

 

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

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 ...post

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

 

這道題給了咱們一個鏈表,讓咱們分開奇偶節點,全部奇節點在前,偶節點在後。咱們能夠使用兩個指針來作,pre指向奇節點,cur指向偶節點,而後把偶節點cur後面的那個奇節點提早到pre的後面,而後pre和cur各自前進一步,此時cur又指向偶節點,pre指向當前奇節點的末尾,以此類推直至把全部的偶節點都提早了便可,參見代碼以下:url

 

解法一:spa

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來保存偶節點的起點位置,而後把奇節點的指向偶節點的下一個(必定是奇節點),此奇節點後移一步,再把偶節點指向下一個奇節點的下一個(必定是偶節點),此偶節點後移一步,以此類推直至末尾,此時把分開的偶節點的鏈表連在奇節點的鏈表後便可,參見代碼以下;指針

 

解法二:code

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 題目講解彙總(持續更新中...)htm

相關文章
相關標籤/搜索