MDGSF Software Engineer

[算法学习][leetcode] 328 Odd Even Linked List

2017-09-05
mdgsf
Art

https://leetcode.com/problems/odd-even-linked-list/description/

题目

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 …

题目翻译

题目解析

参考答案

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

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

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

        if (head->next == NULL)
        {
            return head;
        }

        if (head->next->next == NULL)
        {
            return head;
        }

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

        while (t != NULL)
        {
            even->next = t->next;
            t->next = odd->next;
            odd->next = t;

            odd = t;
            even = even->next;
            if (even == NULL)
            {
                break;
            }
            t = even->next;
        }

        return head;
    }

    ListNode * createList(vector<int> & vecValue)
    {
        ListNode * head = NULL;
        ListNode * tail = NULL;

        vector<int>::iterator iter = vecValue.begin();
        while (iter != vecValue.end())
        {
            ListNode * pNew = new ListNode(*iter);
            if (head == NULL)
            {
                head = pNew;
                tail = pNew;
            }
            else
            {
                tail->next = pNew;
                tail = pNew;
            }

            ++iter;
        }

        return head;
    }

    void vShowList(ListNode * pList)
    {
        while (pList != NULL)
        {
            cout << pList->val << " ";
            pList = pList->next;
        }
        cout << endl;
    }
};

int main()
{
    Solution o;
    vector<int> vecValue = { 1, 2, 3 };
    ListNode * pList = o.createList(vecValue);
    ListNode * pResult = o.oddEvenList(pList);
    o.vShowList(pResult);
    return 0;
}

weixingongzhonghao

Similar Posts

Comments