LeetCode 328. Odd Even Linked List(链表元素按奇偶位置聚集)

The program should run in O(1) space complexity and O(nodes) time complexity.
解题思路:按照位置的奇偶,分别串奇链表和偶链表最后 奇—>偶
(要保存偶链表的真正头结点

public ListNode oddEvenList(ListNode head) {
        //若不加此句,当链表只有一个结点时,ListNode even = head.next; 会报空指针错误
        if(head == null || head.next == null) return head;
        
        //奇链表的工作指针
		ListNode odd = head;
		//偶链表的工作指针
		ListNode even = head.next;
		//偶链表的真正头结点,因为要与奇链表连接
		ListNode evenHead = even;

        //注意条件(分别管总链表数为奇数和偶数)
        while(even != null && even.next != null) {
            odd.next = odd.next.next;
            odd = odd.next;

            even.next = even.next.next;
            even = even.next;
        }
        //奇偶链表连接
        odd.next = evenHead;
        return head;
    }

你可能感兴趣的:(LeetCode分类刷题,#,LeetCode链表)