Odd Even Linked List

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:
Given 1->2->3->4->5->NULL,
return 1->3->5->2->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 ...

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
//328. Odd Even Linked List
class Solution {
public:
    ListNode* oddEvenList(ListNode* head) {
        if(head==NULL){
            return NULL;
        }

        ListNode* odd=head;
        ListNode* even=head->next;
        ListNode* fisrtEven=head->next;

        if(even ==NULL){
            return head;
        }

        while(odd->next && even->next){

            //1->3 odd link  odd->next
            odd->next=odd->next->next;
          //take odd->next whole as pointer
            odd=odd->next;

            even->next=even->next->next;
            even=even->next;
        }

        odd->next=fisrtEven;

        return head;

    }
};

class Solution {
public:
    ListNode* oddEvenList(ListNode* head) {
        if(head==NULL){
            return NULL;
        }

        ListNode* odd=head;
        ListNode* even=head->next;
        ListNode* fisrtEven=head->next;
        ListNode* p=odd;
        ListNode* q=even;
        if(even ==NULL){
            return head;
        }

        while(odd->next && even->next){


            p=p->next->next;
            odd->next=p;
            odd=p;

            q=q->next->next;
            even->next=q;
            even=q;
        }

        odd->next=fisrtEven;
        

        return head;

    }
};

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容