LEEDCODE 328奇偶链表

LEEDCODE 328奇偶链表_第1张图片

/**
 * 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) {
        if(head == nullptr || head->next == nullptr)
        {
            return head;
        }
        ListNode* odd = head;
        ListNode* even = head->next;
        ListNode* cur = even;
        while(odd && even)
        {
            if(even->next)
            {
                odd->next = even->next;
                even->next = odd->next->next;
                even = even->next;
                odd = odd->next;
            }
            else
            {
                odd->next = cur;
                return head;
            }

        }
        odd->next = cur;
        return head;

    }
};

LEEDCODE 328奇偶链表_第2张图片

你可能感兴趣的:(链表,数据结构)