题解 | #链表的奇偶重排#
链表的奇偶重排
http://www.nowcoder.com/practice/02bf49ea45cd486daa031614f9bd6fc3
O(n),O(1)
public ListNode oddEvenList (ListNode head) { // write code here if (head == null || head.next == null) return head; ListNode h1 = head, h2 = head.next; ListNode p1 = h1, p2 = h2; // 你追我赶 while (p1.next != null && p2.next != null){ if (p2.next != null){ p1.next = p2.next; p1 = p1.next; } if (p1.next != null){ p2.next = p1.next; p2 = p2.next; } } // 处理最后一个节点的next指针,否则可能会造成环形链表 p2.next = null; p1.next = h2; return h1; }