leetcode 328 奇偶链表

地址:https://leetcode-cn.com/problems/odd-even-linked-list/
大意:给定一个链表,把所有的奇数节点排在左边,其他排在右边。
要求:时间复杂度O(n) 空间复杂度O(1)

class Solution {
public:
    ListNode* oddEvenList(ListNode* head) {
        if(head == NULL || head->next == NULL || head->next->next == NULL)
            return head;

        ListNode *oneNode = head;
        ListNode *twoNode = head->next;

        ListNode *secendNode = twoNode->next;

        while(twoNode && twoNode->next){
            secendNode = twoNode->next;

            twoNode->next = twoNode->next->next;
            secendNode->next = oneNode->next;
            oneNode->next = secendNode;

            oneNode = oneNode->next;
            twoNode = twoNode->next;
        }
        return head;
    }
};

猜你喜欢

转载自www.cnblogs.com/c21w/p/12683498.html
今日推荐