LeetCode328. 奇偶連結串列
阿新 • • 發佈:2020-12-13
思路1:類似LeetCode86. 分隔連結串列,設定兩個虛擬頭節點,最後拼接即可。
☆☆思路2:分離節點後合併,不需要設定虛擬頭節點
class Solution { public ListNode oddEvenList(ListNode head) { if (head == null || head.next == null) return head; /** * 方法1:設定兩個虛擬頭節點 */ /* ListNode dummyHead1 = new ListNode(0); ListNode dummyHead2 = new ListNode(0); ListNode node1 = dummyHead1; ListNode node2 = dummyHead2; int cnt = 1; while (head != null) { if ((cnt & 1) == 1) { node1.next = head; node1 = node1.next; }else { node2.next = head; node2 = node2.next; } head = head.next; cnt ++; } node2.next = null; node1.next = dummyHead2.next; return dummyHead1.next;*/ /** * 方法2:不需要設定虛擬頭節點 */ ListNode evenHead = head.next; // 偶數連結串列的頭節點 ListNode odd = head, even = head.next; 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; } }