Dijkstra's algorithm, which lets you answer "What's the shortest path to X?" for weighted graphs.

Dijkstra's 就是在weighted graph 中选出最小值路径
今天完成了每日一题,发现mergesort里面基本的构成就是拆分和merge,这两个你掌握了基本就可以熟练使用了。下面是今天练习的代码:
public ListNode sortList(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode mid = findMid(head);
ListNode left = sortList(head);
ListNode right = sortList(mid);
return merge(left, right);
}
private ListNode findMid(ListNode head) {
ListNode slow = null, fast = head;
while (fast != null && fast.next != null) {
slow = (slow == null) ? head : slow.next;
fast = fast.next.next;
}
ListNode res = slow.next;
//cut off (split the listnode)
slow.next = null;
return res;
}
private ListNode merge(ListNode l1, ListNode l2) {
ListNode prehead = new ListNode();
ListNode prev = prehead;
while (l1 != null && l2 != null) {
if (l1.val <= l2.val) {
prev.next = l1;
l1 = l1.next;
} else {
prev.next = l2;
l2 = l2.next;
}
prev = prev.next;
}
prev.next = (l1 == null) ? l2 : l1;
return prehead.next;
}
网友评论