双指针法
合并两个排序的链表
http://www.nowcoder.com/questionTerminal/d8b6b4358f774294a89de2a6ac4d9337
public static ListNode Merge(ListNode list1, ListNode list2) {
if (list1 == null && list2 == null) {
return null;
} else if (list1 == null) {
return list2;
} else if (list2 == null) {
return list1;
}
ListNode p1 = list1;
ListNode p2 = list2;
ListNode dumpy = new ListNode(-1);
ListNode curr = dumpy; // 将当前指针指向头节点
dumpy.next = p1.val < p2.val ? p1 : p2;
while (p1 != null && p2 != null) {
if (p1.val <= p2.val) {
curr.next = p1;
p1 = p1.next;
} else {
curr.next = p2;
p2 = p2.next;
}
curr = curr.next; // 当前指针向后移动
}
// 注意:如果p1为空,则最后一个元素为p2,反之亦然
curr.next = p1 != null ? p1 : p2;
return dumpy.next;
}
