Loading

【leetcode】328. Odd Even Linked List

  Given the head of a singly linked list, group all the nodes with odd indices together followed by the nodes with even indices, and return the reordered list. The first node is considered odd, and the second node is even, and so on. Note that the relative order inside both the even and odd groups should remain as it was in the input. You must solve the problem in O(1) extra space complexity and O(n) time complexity. 

Example 1:

Input: head = [1,2,3,4,5]
Output: [1,3,5,2,4]

Example 2:

Input: head = [2,1,3,5,6,4,7]
Output: [2,3,6,7,1,5,4]
  这道题要仔细读一下题意,是将偶数位置的节点放在前面,奇数位置的节点放在尾端,并不是按照node中的val值进行奇偶分组,头节点可以认为是从0开始的,然后用一个指针遍历
这个链表,将偶数位置以及奇数位置的节点取出来分别构成两个新链表,最后再拼接一下即可。
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* oddEvenList(ListNode* head) {
        
        ListNode* odd=new ListNode();
        ListNode* even=new ListNode();
        ListNode* node=head;
        ListNode* odd_end=odd;
        ListNode* even_end=even;
        int i=0;
        
        while(node){
            if(i&1){
                //奇数
                odd_end->next=node;
                odd_end=odd_end->next;
            }
            else{
                even_end->next=node;
                even_end=even_end->next;
            }
            node=node->next;
            i++;
        }
        odd_end->next=nullptr;
        even_end->next=odd->next;
        return even->next;     
    }
};

 

 
posted @ 2021-12-02 15:58  aalanwyr  阅读(36)  评论(0编辑  收藏  举报