题解 | #链表的奇偶重排#

链表的奇偶重排

http://www.nowcoder.com/practice/02bf49ea45cd486daa031614f9bd6fc3

odd 连接奇数节点
even 连接偶数节点
最终让odd尾指向even头就好了

class Solution {
public:
    ListNode* oddEvenList(ListNode* head) {
        if(!head || head->next == nullptr) 
            return head;
        ListNode* odd = nullptr, *oddEnd = nullptr;
        ListNode* even = nullptr, *evenEnd = nullptr;
        while(head){
            ListNode* cur = head;
            head = head->next;
            if(!odd) odd = oddEnd = cur;
            else{
                oddEnd->next = cur;
                oddEnd = cur;
            }
            if(head){
                cur = head;
                head = head->next;
                if(!even) even = evenEnd = cur;
                else{
                    evenEnd->next = cur;
                    evenEnd = cur;
                    evenEnd->next = nullptr;
                }
            }
        }
        oddEnd->next = even;
        return odd;
    }
};

优化简化代码

class Solution {
public:
    ListNode* oddEvenList(ListNode* head) {
        if(!head || head->next == nullptr) 
            return head;
        ListNode* odd = nullptr, *oddEnd = nullptr;
        ListNode* even = nullptr, *evenEnd = nullptr;
        while(head){
            !odd?oddEnd = odd = head : oddEnd = oddEnd->next=head;
            head = head->next;
            if(head){
                ListNode* cur = head;
                head = head->next;
                !even?even = evenEnd = cur:evenEnd = evenEnd->next = cur;
                evenEnd->next = nullptr;
            }
        }
        oddEnd->next = even;
        return odd;
    }
};
全部评论

相关推荐

点赞 评论 收藏
分享
jack_miller:我给我们导员说我不在这里转正,可能没三方签了。导员说没事学校催的时候帮我想办法应付一下
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务