leetcode-Odd Even Linked List

题目链接:https://leetcode.com/problems/odd-even-linked-list/

题目很简单,注意哑巴节点的使用,可以简化复杂度

代码如下:

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

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

        ListNode *p1 = &dummy1;
        ListNode *p2 = &dummy2;
        ListNode *p = head;
        int count = 0;
        while(p != NULL)
        {
            ++count;
            if(count % 2 == 1)
            {
                p1->next = p;
                p1 = p1->next;
            }
            else
            {
                p2->next = p;
                p2 = p2->next;
            }
            p = p->next;
        }
        p1->next = dummy2.next;
        p2->next = NULL;
        return dummy1.next;
    }
};

 

posted @ 2016-05-15 22:20  Shirley_ICT  阅读(95)  评论(0编辑  收藏  举报