leetcode之Odd Even Linked List

来源:互联网 发布:千百撸最新域名 编辑:程序博客网 时间:2024/05/03 13:22

题目:

Given a singly linked list, group all odd nodes together followed by the even nodes. Please note here we are talking about the node number and not the value in the nodes.

You should try to do it in place. The program should run in O(1) space complexity and O(nodes) time complexity.

解答:

只需要将所有的奇节点先串成一个链,将所有偶数节点串成一个链,然后连接起来即可,所以需要记录奇节点链的尾节点,偶节点链的初始节点

和结束节点,然后原地进行置换即可

class Solution {
public:
    ListNode* oddEvenList(ListNode* head) {
        if(!head)
            return head;
        if(!head->next)
            return head;
        ListNode* oddLast = head;
        ListNode* evenStart = head->next, *evenLast = head->next;
        while(evenLast && evenLast->next)
        {
            oddLast->next = evenLast->next;
            oddLast = oddLast->next;
            evenLast->next = oddLast->next;
            evenLast = oddLast->next;
        }
        oddLast->next = evenStart;
        return head;
    }
};

0 0