package com.my.util;
public class SingleNode {
public int value;
public SingleNode next;
public SingleNode(int data){
this.value = data;
}
}
package com.my.suanfa;
import com.my.util.SingleNode;
public class Solution16 {
public SingleNode merge(SingleNode head1, SingleNode head2) {
if(head1 == null || head2 == null) {
return head1 != null ? head1 : head2;
}
SingleNode head = head1.value < head2.value ? head1 : head2;
SingleNode cur1 = head == head1 ? head1 : head2;
SingleNode cur2 = head == head1 ? head2 : head1;
SingleNode pre = null;
SingleNode next = null;
while(cur1 != null && cur2 != null) {
if(cur1.value <= cur2.value) {
pre = cur1;
cur1 = cur1.next;
} else {
next = cur2.next;
pre.next = cur2;
cur2.next = cur1;
pre = cur2;
cur2 = next;
}
}
pre.next = cur1 != null ? cur1 : cur2;
return head;
}
}