Reorder List
问题:
Given a singly linked list L: L0→L1→…→Ln-1→Ln,
reorder it to: L0→Ln→L1→Ln-1→L2→Ln-2→…
You must do this in-place without altering the nodes' values.
思路:
使用HashMap记录位置,数学简易推导,进行List的变换
我的代码:
public class Solution { public void reorderList(ListNode head) { if(head == null) return; int count = 0; HashMap<Integer,ListNode> hm = new HashMap<Integer,ListNode>(); while(head != null) { hm.put(count++,head); head = head.next; } int sum = count - 1; for(int i = 0; i < count/2; i++) { ListNode cur = hm.get(i); ListNode next = hm.get(i + 1); ListNode last = hm.get(sum - i); cur.next = last; last.next = next; next.next = null; } return; } }
他人代码:
public class Solution { private ListNode start; public void reorderList(ListNode head) { // 1. find the middle point if(head == null || head.next == null || head.next.next == null)return; ListNode a1 = head, a2 = head; while(a2.next!=null){ // a1 step = 1 a1 = a1.next; // a2 step = 2 a2 = a2.next; if(a2.next==null)break; else a2 = a2.next; } // a1 now points to middle, a2 points to last elem // 2. reverse the second half of the list this.reverseList(a1); // 3. merge two lists ListNode p = head, t1 = head, t2 = head; while(a2!=a1){ // start from both side of the list. when a1, a2 meet, the merge finishes. t1 = p; t2 = a2; p = p.next; a2 = a2.next; t2.next = t1.next; t1.next = t2; } } // use recursion to reverse the right part of the list private ListNode reverseList(ListNode n){ if(n.next == null){ // mark the last node // this.start = n; return n; } reverseList(n.next).next = n; n.next = null; return n; } }
学习之处:
- 他人的代码的思路更好,因为节省了空间,最后还是转换成了追击问题,通过追击问题,确定中间点进行分割,前面List和反转后的后面List进行Merge