【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.


思路:
比较简单,直接设置两个头结点——odd头结点和even头结点,分别把各个节点挂上去即可。


代码实现:
submit一次就过了。

/**
 * 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:
    ListNode* oddEvenList(ListNode* head) {
        if (head == nullptr){
            return nullptr;
        }
        ListNode *odd_superhead = new ListNode();
        ListNode *even_superhead = new ListNode();
        ListNode *odd_p = odd_superhead;
        ListNode *even_p = even_superhead;
        ListNode *p = head;
        
        bool isOdd = true;
        while (p){
            if (isOdd){
                odd_p->next = p;
                odd_p = odd_p->next;
            }else{
                even_p->next = p;
                even_p = even_p->next;
            }
            p = p->next;
            isOdd = 1 - isOdd;
        }
        
        odd_p->next = even_superhead->next;
        even_p->next = nullptr;
        
        return odd_superhead->next;
    }
};

discuss:

// 思路:设置两个指针odd和even,分别指向第一个node和第二个node。然后不断地将odd->next指向odd->next->next(even也一样)即可。
class Solution {
public:
    ListNode* oddEvenList(ListNode* head) {
        if (!head) return head;
        ListNode *odd = head, *evenhead = head->next, *even = evenhead;
        
        while (even && even->next){ // 因为even更靠后一点,所以用even判断是否结尾
            odd->next = odd->next->next;
            even->next = even->next->next;
            odd = odd->next;
            even = even->next;
        }
        
        odd->next = evenhead;
        return head;
        
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值