题目描述:
给定两个有序单链表的头结点head1和head2,请合并两个有序链表,合并后的链表依然有序,并返回合并后链表的头结点。
例如:
0—>2—>3—>7—>NULL
1—>3—>5—>7—>9—>NULL
合并后的链表为:0—>1—>2—>3—>3—>5—>7—>7—>9—>NULL
要求:假设两个链表的长度分别为M和N,时间复杂度为O(M + N),额外空间复杂度O(1)
思路:有两种实现方式,一种是将一个有序的链表插入到另一个头结点较小的有序的链表中,插入节点时,要注意记录插入位置的前一个和后一个节点,并且要注意一下在一下的实现方式中,如何在两个链表的头结点值的大小不确定的情况中,寻找值较小的头结点,第二种是依次比较两个链表节点值的大小,将较小的节点从原来节点上面摘下来,重新组成一个有序的链表
public class Code_018_MergeList {
public static class Node {
public int data;
public Node next;
public Node(int data) {
this.data = data;
}
}
//第二种实现方式
public static Node merge1(Node head1, Node head2) {
if (head1 == null || head2 == null) {
return head1 != null ? head1 : head2;
}
Node dummyHead = new Node(-1); //虚拟头结点
Node cur = dummyHead;
while(head1 != null && head2 != null) {
if (head1.data <= head2.data) {
cur.next = head1;
cur = head1;
head1 = head1.next;
cur.next = null;
} else {
cur.next = head2;
cur = head2;
head2 = head2.next;
cur.next = null;
}
}
cur.next = head1 == null ? head2 : head1;
return dummyHead.next;
}
//第一种实现方式
public static Node merge2(Node head1, Node head2) {
if (head1 == null || head2 == null) {
return head1 != null ? head1 : head2;
}
Node head = head1.data <= head2.data ? head1 : head2;
Node cur1 = head == head1 ? head1 : head2;
Node cur2 = head == head1 ? head2 : head1;
Node prev = null;
Node next = null;
while(cur1 != null && cur2 != null) {
if (cur1.data <= cur2.data) {
prev = cur1;
cur1 = cur1.next;
} else {
next = cur2.next;
prev.next = cur2;
cur2.next = cur1;
prev = cur2;
cur2 = next;
}
}
prev.next = cur1 == null ? cur2 : cur1;
return head;
}
}