面试题 08.06. 汉诺塔问题
class Solution {
public void hanota(List<Integer> A, List<Integer> B, List<Integer> C) {
if(A==null) return;
recurse(A, B, C, A.size());
}
public void recurse(List<Integer> src, List<Integer> tmp, List<Integer> tar, int num) {
if(num<=0) return;
recurse(src, tar, tmp, num-1);
tar.add(src.remove(src.size()-1));
recurse(tmp, src, tar, num-1);
}
}
148. 排序链表
class Solution {
public ListNode sortList(ListNode head) {
int size = getSize(head);
int nLen = 1;
ListNode dumbHead = new ListNode(Integer.MIN_VALUE, head);
ListNode prev, currHead;
ListNode l1, l2;
int i;
while (nLen < size) {
prev = dumbHead; currHead = dumbHead.next;
while (currHead != null) {
l1 = currHead; l2 = currHead;
i = 1;
while (i <= nLen && l2.next != null) {
l2 = l2.next;
i++;
}
if (i <= nLen) break;
currHead = l2;
i = 1;
while (i <= nLen && currHead != null) {
currHead = currHead.next;
i++;
}
prev = mergeListNode(prev, currHead, l1, nLen, l2, i-1);
}
nLen *= 2;
}
return dumbHead.next;
}
private int getSize(ListNode node) {
int size = 0;
while (node != null) {
size++;
node = node.next;
}
return size;
}
private ListNode mergeListNode(ListNode prev, ListNode nextHead, ListNode l1, int e1, ListNode l2, int e2) {
while (e1 > 0 && e2 > 0) {
if (l1.val <= l2.val) {
prev.next = l1;
l1 = l1.next;
e1--;
} else {
prev.next = l2;
l2 = l2.next;
e2--;
}
prev = prev.next;
}
prev.next = l1;
int r = e1;
if (e1 <= 0) {
prev.next = l2;
r = e2;
}
while (r-- > 0) {
prev = prev.next;
}
prev.next = nextHead;
return prev;
}
}