143. 重排連結串列
阿新 • • 發佈:2020-07-27
class Solution { public void reorderList(ListNode head) { if(head == null || head.next == null || head.next.next == null) return; ListNode mid = findMid(head); // 找到中間節點 ListNode node2 = mid.next; mid.next = null; merge(head,reverse(node2)); // 翻轉後面一段連結串列,並與前一段連結串列合併} public ListNode findMid(ListNode head) { ListNode fast = head, slow = head; while(fast != null && fast.next != null) { fast = fast.next.next; slow = slow.next; } return slow; } public ListNode reverse(ListNode head) {if(head == null || head.next == null) return head; ListNode node = reverse(head.next); head.next.next = head; head.next = null; return node; } public ListNode merge(ListNode node1,ListNode node2) { if(node1 == null) return node2; if(node2 == null) return node1; ListNode next = node1.next; node1.next = node2; node2.next = merge(next,node2.next); return node1; } }