欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

LeetCode 328. 奇偶链表(注意成环)

程序员文章站 2022-05-20 19:10:21
...

奇偶链表

/**
 * 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 || !head->next) return head;
        ListNode *p1 = head, *p2 = head->next;
        ListNode *move1 = p1, *move2 = p2;

        ListNode* cur = head->next->next;
        int i = 2;
        while(cur){
            if(i&1){
                move2->next = cur;
                move2 = cur;
            }else{
                move1->next = cur;
                move1 = cur; 
            }
            cur = cur->next;
            i++;

        }
        // 否则会成环的!
        move2->next = nullptr;
        move1->next = p2;
        return p1;
    }
};
相关标签: LeetCode # LC链表