328. 奇偶链表
小于 1 分钟
328. 奇偶链表中等
解法:
定义两个指针,odd,even 交替移动,将经过的结点存贮给 odds 和 evens
class Solution {
public ListNode oddEvenList(ListNode head) {
if(head == null || head.next == null) return head;
ListNode odd = head;
ListNode even = head.next;
ListNode odds = head;
ListNode oddFir = odds;
ListNode evens = head.next;
ListNode evenFir = evens;
while (true){
if(even.next != null){
odds.next = even.next;
odd = even.next;
odds = odds.next;
}else {
odd.next = null;
odds.next = evenFir;
return oddFir;
}
if(odd.next != null){
evens.next = odd.next;
even = odd.next;
evens = evens.next;
}else {
even.next = null;
odd.next = evenFir;
return oddFir;
}
}
}
}
Powered by Waline v2.15.5