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

链表的奇偶重排

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

/**
 * struct ListNode {
 *	int val;
 *	struct ListNode *next;
 *	ListNode(int x) : val(x), next(nullptr) {}
 * };
 */
class Solution {
public:
    ListNode* oddEvenList(ListNode* head) {
        // write code here
        if( head==nullptr || 
            head->next==nullptr ||    
            head->next->next==nullptr)
            return head;
        ListNode* cur = head->next->next;
        ListNode* once_ou = head->next;
        ListNode* ji=head;
        ListNode* ou = head->next;
        int count=3;
        while(cur)
        {
           if(count & 1){
                ji->next = cur;
                ji = cur;
           }else{
                ou->next = cur;
                ou=cur;
           }
           ++count;
           cur = cur->next;
        }
        ou->next = nullptr;
        ji->next = once_ou;
        return head;
    }
};

全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务