Article From:https://www.cnblogs.com/yaoyudadudu/p/9216204.html

Description of the problem:

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 1:

Input: 1->2->3->4->5->NULL
Output: 1->3->5->2->4->NULL

Example 2:

Input: 2->1->3->5->6->4->7->NULL
Output: 2->3->6->7->1->5->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 …

 

The idea of solving the problem:

This question allows us to link odd number nodes together to connect even digit nodes.

So we can use two pointers to record the beginning of odd digit (oddStart) and even digit (evenStart).

Then the traversal is used to link new nodes to odd numbers and odd numbers respectively.

It is important to note that:

if(temp->next)
     temp->next = temp->next->next;

The condition of judgment here, if there is a mistakeDead cycle!!!(Because the last node does not connect to NULL)

 

Code:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* oddEvenList(ListNode* head) {
        if(!head || !head->next)
            return head;
        ListNode* oddStart = head;
        ListNode* evenStart = head->next;
        ListNode* cur = oddStart;
        ListNode* prev = cur;
        while(cur && cur->next){
            ListNode* temp = cur->next;
            cur->next = temp->next;
            if(temp->next)
                temp->next = temp->next->next;
            prev = cur;
            cur = cur->next;
        }
        if(cur){
            cur->next = evenStart;
        }else{
            prev->next = evenStart;
        }
        return head;
    }
};

 

Link of this Article: 328. Odd Even Linked List

Leave a Reply

Your email address will not be published. Required fields are marked *