样例
head1:2 4 6 8 10,head2:1 3 5 7 9,结果:1 2 3 4 5 6 7 8 9 10
java代码
/**
* @Description:合并两个有序的单链表
* @Author: lizhouwei
* @CreateDate: 2018/4/7 17:27
* @Modify by:
* @ModifyDate:
*/
public class Chapter2_19 {
public Node mergeSortLink(Node head1, Node head2) {
if (head1 == null || head2 == null) {
return head1 == null ? head2 : head1;
}
Node head = null;
Node pre = null;
Node next = null;
Node cur1 = null;
Node cur2 = null;
head = head1.vlaue < head2.vlaue ? head1 : head2;
cur1 = head1.vlaue < head2.vlaue ? head1 : head2;
cur2 = head1.vlaue < head2.vlaue ? head2 : head1;
while (cur1 != null && cur2 != null) {
if (cur1.vlaue < cur2.vlaue) {
pre = cur1;
cur1 = cur1.next;
} else {
next = cur2.next;
pre.next = cur2;
cur2.next = cur1;
pre = cur2;
cur2 = next;
}
}
pre.next = cur2 != null ? cur2 : cur1;
return head;
}
//测试
public static void main(String[] args) {
Chapter2_19 chapter = new Chapter2_19();
Link link1 = new Link();
Link link2 = new Link();
//构造链表
for (int i = 10; i > 0; i=i-2) {
link1.add(i);
}
for (int i = 9; i > 0; i=i-2) {
link2.add(i);
}
Link.printLink(link1.head);
Link.printLink(link2.head);
Node head = chapter.mergeSortLink(link1.head, link2.head);
Link.printLink(head);
}
}