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

328. Odd Even Linked List。

程序员文章站 2022-07-14 08:45:35
...

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.


这题比较简单。就是将奇数节点和偶数节点进行分离,然后奇数串在一起,偶数串在一起,最后偶数跟在奇数的后面就好了。使用一个int变量从1开始进行+1,就可以使用对2取模运算根据计算结果是1还是0就好了。然后分别将奇数偶数串起来就好了,需要注意一下最后一个偶数节点(因为偶数在奇数后面)可能next指向的不为空,这时候需要手动赋值为空。

#include <iostream>
#include <unordered_set>
using namespace std;

struct ListNode {
    int val;
    ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
};

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

        ListNode* oddNode = NULL;//奇数节点
        ListNode* evenNode = NULL;//偶数节点
        ListNode* p1;
        ListNode* p2;
        int num = 1;

        while(head) {
            if(num%2 == 1) {//奇数节点
                if(!oddNode) {
                    oddNode = head;
                } else {
                    p1->next = head;
                }
                p1 = head;
            }
            if(num%2 == 0) {//偶数节点
                if(!evenNode) {
                    evenNode = head;
                } else {
                    p2->next = head;
                }
                p2 = head;
            }
            //cout << p1->val << ",";
            //cout << p2->val << endl;
            head = head->next;
            num++;
        }
        //cout << p1->val << ",";
        //cout << p2->val << endl;
        //cout << oddNode->val << ",";
        //cout << evenNode->val << endl;
        p1->next = evenNode;
        p2->next = NULL;
        return oddNode;
    }
};

int main() {
    Solution s;


    ListNode node1(1);
    ListNode node2(2);
    ListNode node3(3);
    ListNode node4(4);
    ListNode node5(5);

    node1.next = &node2;
    node2.next = &node3;
    node3.next = &node4;
    node4.next = &node5;

    ListNode* p = s.oddEvenList(&node1);

    while(p) {
        cout << p->val;
        cout << endl;
        p = p->next;
    }

}


运行结果可能有误差。

328. Odd Even Linked List。