[ Skill ] 圖形化元件在註冊 User Trigger 時需要注意的事情
阿新 • • 發佈:2021-12-01
給定一個單鏈表 L 的頭節點 head ,單鏈表 L 表示為:
L0 → L1 → … → Ln - 1 → Ln
請將其重新排列後變為:
L0 → Ln → L1 → Ln - 1 → L2 → Ln - 2 → …
不能只是單純的改變節點內部的值,而是需要實際的進行節點交換。
來源:力扣(LeetCode)
連結:https://leetcode-cn.com/problems/reorder-list
著作權歸領釦網路所有。商業轉載請聯絡官方授權,非商業轉載請註明出處。
心之所向,素履以往 生如逆旅,一葦以航class Solution { private static ListNode reverse(ListNode head) { ListNode pre = null, cur = head, next; while (cur != null) { next = cur.next; cur.next = pre; pre = cur; cur = next; } return pre; } /** * 上中節點 * * @param head * @return */ private static ListNode findMid(ListNode head) { if (head == null || head.next == null || head.next.next == null) { return head; } ListNode slow = head.next; ListNode fast = head.next.next; while (fast.next != null && fast.next.next != null) { slow = slow.next; fast = fast.next.next; } return slow; } private static ListNode merge(ListNode head1, ListNode head2) { ListNode newHead = new ListNode(), tail = newHead; while (head1 != null && head2 != null) { ListNode next1 = head1.next; ListNode next2 = head2.next; tail.next = head1; tail = tail.next; tail.next = null; tail.next = head2; tail = head2; tail.next = null; head1 = next1; head2 = next2; } if (head1 != null) { tail.next = head1; } if (head2 != null) { tail.next = head2; } return newHead.next; } private static ListNode[] split(ListNode head) { ListNode newHead1 = new ListNode(), tail1 = newHead1; ListNode newHead2 = new ListNode(), tail2 = newHead2; while (head != null) { tail1.next = head; tail1 = head; head = head.next; tail1.next = null; if (head != null) { tail2.next = head; tail2 = head; head = head.next; tail2.next = null; } } return new ListNode[]{newHead1.next, newHead2.next}; } public static void reorderList(ListNode head) { if (head == null || head.next == null || head.next.next == null) { return; } ListNode mid = findMid(head); ListNode midNext = mid.next; mid.next = null; ListNode head1 = head; ListNode head2 = reverse(midNext); merge(head1, head2); } } class ListNode { int val; ListNode next; ListNode() { } ListNode(int val) { this.val = val; } ListNode(int val, ListNode next) { this.val = val; this.next = next; } }