leetcode-Odd Even Linked List-328

把链表的第奇数个节点方在一起,第偶数的节点在后半部分,要求空间O1,时间ON

看的这位网友的,思考为什么这样空间是O1

http://www.cnblogs.com/pkuYang/p/5135542.html

/**
 * Definition for singly-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||head->next->next==NULL) return head;
        ListNode* first=head;
        ListNode* second=head->next;
        ListNode* even=second;
        while(second->next){
            ListNode* p=second->next;
            first->next=p;
            first=p;
            if(p->next){
                second->next=p->next;
                second=p->next;
            }
            else{
                second->next=NULL;
                break;
            }
        }
        first->next=even;
        return head;
    }
};


你可能感兴趣的:(leetcode)