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

链表的奇偶重排

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

模拟

借助两个vector模拟即可

C++代码:

class Solution {
public:
    ListNode* oddEvenList(ListNode* head) {
        if (!head) {return NULL;}
        if (head->next == NULL) {
            return head;
        }
        vector<ListNode *> a, b;
        for (int i = 0; head; i++, head = head->next) {
            if (i & 1) {
                b.push_back(head);
            } else {
                a.push_back(head);
            }
        }
        for (int i = 0; i < a.size() - 1; i++) {
            a[i]->next = a[i + 1];
        }
        for (int i = 0; i < b.size() - 1; i++) {
            b[i]->next = b[i + 1];
        }
        a[a.size() - 1]->next = b[0];
        b[b.size() - 1]->next = NULL;
        return a[0];
    }
};
全部评论

相关推荐

05-22 12:44
已编辑
门头沟学院 golang
点赞 评论 收藏
分享
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务