2018-04-23 14:34:09
一、Odd Even Linked List
问题描述:
问题求解:
如果思考从swap角度来解决问题就会陷入一个误区,其实直接使用链表的指针分别构造出odd和even即可。
public ListNode oddEvenList(ListNode head) { if (head == null || head.next == null) return head; ListNode odd = head, even = head.next, evenHead = even; while (even != null && even.next != null) { odd.next = odd.next.next; even.next = even.next.next; odd = odd.next; even = even.next; } odd.next = evenHead; return head; }
二、Reorder List
问题描述:
问题求解:
step1:找到中点
step2:把后半段反转,使用插入法
step3:然后开始执行一轮的插入操作
public void reorderList(ListNode head) { if (head == null || head.next == null) return; ListNode slow = head, fast = head; while (fast != null && fast.next != null) { slow = slow.next; fast = fast.next.next; } ListNode cur = slow.next; ListNode then = null; while (cur != null && cur.next != null) { then = cur.next; cur.next = then.next; then.next = slow.next; slow.next = then; } cur = head; while (slow.next != null) { ListNode tmp = cur.next; ListNode toInsert = slow.next; slow.next = toInsert.next; toInsert.next = cur.next; cur.next = toInsert; cur = tmp; } }