328. Odd Even Linked List

来源:互联网 发布:淘宝内衣店铺名字大全 编辑:程序博客网 时间:2024/06/07 04:43

328. Odd Even Linked List

    Medium难度

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.

题目理解

这道题难度不是特别大,就是按顺序(由小到大)找每一个奇数节点然后放到尾巴后面就好。于是就要先确定链表的大小,这里我是用一个简单的循环解决。接下来就要去把所有找到的奇数节点放到尾巴后面,并且将end更新为新end即可。复杂度只有长度的1/2。唯一要注意的是。只有三个节点时不需要这些操作,要单独处理。

代码部分

/**
 * 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) 
{
return head;
}
        ListNode* last = head;
        int cnt = 1;
        for(; last->next; last = last->next, ++cnt);        
if(cnt < 3) 
{
return head;

        ListNode* now = head;
        ListNode* end = last;
        for(int i = 0; i< cnt/2;  i++)
{
            ListNode*
a= now->next;
            now->next =
a->next;
            end->next =
a;
           
a->next = NULL;
            end =
a;
            now = now->next;
        }
        return head;
    }
};

1 0
原创粉丝点击