2020/11/13 328. 奇偶链表

每日一题训练

class Solution {
    public ListNode oddEvenList(ListNode head) {
        if(head==null||head.next==null){
            return head;
        }
        ListNode cur=head;
        ListNode pre_even=new ListNode(0);
        ListNode even=pre_even;
        ListNode pre=new ListNode(0);
        ListNode odd=pre;
        int count=1;
        while(cur!=null){
            if(count%2==1){
                odd.next=cur;
                odd=cur;
                cur=cur.next;
                odd.next=null;
            }
            if(count%2==0){
                even.next=cur;
                even=even.next;
                cur=cur.next;
                even.next=null;
            }
            count++;
        }
        odd.next=pre_even.next;
        return pre.next;
    }
}

官方题解
为什么空间复杂度比我写的还要大呢?
是不是因为while循环多进行了判断

class Solution {
    public ListNode oddEvenList(ListNode head) {
        if (head == null) {
            return head;
        }
        ListNode evenHead = head.next;
        ListNode odd = head, even = evenHead;
        while (even != null && even.next != null) {
            odd.next = even.next;
            odd = odd.next;
            even.next = odd.next;
            even = even.next;
        }
        odd.next = evenHead;
        return head;
    }
}

作者:LeetCode-Solution
链接:https://leetcode-cn.com/problems/odd-even-linked-list/solution/qi-ou-lian-biao-by-leetcode-solution/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值