每日一题训练
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)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。