1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 | /** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ public class Solution { public void reorderList(ListNode head) { if (head == null || head.next == null) return; ListNode slow = head; ListNode fast = head; while (fast.next != null && fast.next.next != null){ slow = slow.next; fast = fast.next.next; } ListNode list1 = head; ListNode mid = slow.next; slow.next = null; ListNode list2 = reverse(mid); boolean isList1 = true; ListNode dummy = new ListNode(-1); ListNode previous = dummy; while (list2 != null){ if (isList1){ previous.next = list1; list1 = list1.next; } else{ previous.next = list2; list2 = list2.next; } previous = previous.next; isList1 = !isList1; } if (list1 != null){ previous.next = list1; } return; } private ListNode reverse(ListNode root){ if (root == null || root.next == null) return root; ListNode previous = root; ListNode current = root.next; previous.next = null; while (current != null){ ListNode next = current.next; current.next = previous; previous = current; current = next; } return previous; } } |
Saturday, November 14, 2015
[leetcode] Reorder List
某些地方写得不够短 例如loop里面可以一次接两个instead of 用个boolean来判断哪次接哪个
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment