leetcode 328. Odd Even Linked List | 328. 奇偶链表(Java)
生活随笔
收集整理的這篇文章主要介紹了
leetcode 328. Odd Even Linked List | 328. 奇偶链表(Java)
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
題目
https://leetcode.com/problems/odd-even-linked-list/
題解
要注意的是,因?yàn)橹粚⑴紨?shù)位置的節(jié)點(diǎn) append 到最后,所以用于判斷停止的 tail 節(jié)點(diǎn)不一定是最后一個(gè)節(jié)點(diǎn)。這種情況下,不要遺失了 tail.next 節(jié)點(diǎn)。
class Solution {public ListNode oddEvenList(ListNode head) {if (head == null) return null;if (head.next == null || head.next.next == null) return head;ListNode tail = head;while (tail.next != null && tail.next.next != null) {tail = tail.next.next;}ListNode newTail = tail;ListNode pre = head;ListNode cur = head.next;while (cur != tail) {// cur 摘出來(lái)pre.next = cur.next;pre = pre.next;// cur 放到末尾cur.next = newTail.next;newTail.next = cur;newTail = cur;if (pre == tail) break;cur = pre.next;}return head;} }總結(jié)
以上是生活随笔為你收集整理的leetcode 328. Odd Even Linked List | 328. 奇偶链表(Java)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 324. Wiggle Sort II
- 下一篇: leetcode 162. Find P