leetcode328 - Odd Even Linked List

博客围绕LeetCode上的一道链表题目展开,题目要求将单链表的奇数节点和偶数节点分组,且要原地操作,满足O(1)空间复杂度和O(nodes)时间复杂度。博主采用先保存偶数节点,再插入原链表末尾的方法解决,速度超过73.59%。

题目:
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.
这道题我是先把偶数节点保存下来,然后再插入到原链表的末尾就行了
(faster 73.59%)

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    int getLength(ListNode* head){
        int count = 0;
        while(head != NULL)
        {
            count++;
            head = head->next;
        }
        return count;
    }
    ListNode* oddEvenList(ListNode* head) {
        auto cnt = getLength(head);
        ListNode* head1 = new ListNode;
        ListNode* p = head1;
        ListNode*r, *s;
        r = head;
        int i = 1;
        while(i < cnt){
            if(i % 2 != 0){
                s = r->next;
                p->next = s;
                p = s;
                r->next = r->next->next;
                i++;
            }
            i++;
            r = r ->next;
        }
        p->next = nullptr;
        r = head;
        if(r == nullptr)return head;
        while(r->next != NULL){
            r = r->next;
        }
        r->next = head1->next;
        return head;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值