Categories
不学无术

LeetCode 328. Odd Even Linked List

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.
Example:
Given 1->2->3->4->5->NULL,
return 1->3->5->2->4->NULL.
Note:
The relative order inside both the even and odd groups should remain as it was in the input.
The first node is considered odd, the second node even and so on …

思路

既然是要O(n)时间复杂度,并且O(1)空间复杂度,基本就能想到要用俩指针了。其中一个指针指向当前的奇数位元素,另一个指向偶数位的。
LeetCode328
大概就是这个意思啦,然后指针不断往前挪动。注意要保存偶数指针的头,因为奇数结束之后要串上偶数的~

代码

里面的oddTail是为了防止链表长度为奇数的时候,里面currOdd指针走到NULL的情况。

/**
 * 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)
            return head;
        ListNode* currOdd = head;
        ListNode* currEven = head->next;
        ListNode* evenHead = currEven;
        ListNode* oddTail = currOdd;
        while(currOdd != NULL && currEven != NULL){
            currOdd->next =currEven->next;
            if(currOdd->next != NULL)
                currEven->next = currOdd->next->next;
            oddTail = currOdd;
            currOdd = currOdd->next;
            currEven = currEven->next;
        }
        if(currOdd != NULL)
            currOdd->next = evenHead;
        else
            oddTail->next = evenHead;
        return head;
    }
};

 

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.