)将两个递增的有序链表合并为一个递增的有序 链表。要求结果链表仍使用原来两个链表的存储空 间,不另外占用其它的存储空间。表中不允许有重 复的数据。java
时间: 2023-05-29 08:05:16 浏览: 78
两个有序链表,合成为一个有序链表
public class MergeSortedLinkedList {
public static void main(String[] args) {
//创建两个有序链表
Node head1 = new Node(1);
head1.next = new Node(3);
head1.next.next = new Node(5);
Node head2 = new Node(2);
head2.next = new Node(4);
head2.next.next = new Node(6);
//合并两个有序链表
Node mergedHead = merge(head1, head2);
//打印合并后的链表
Node temp = mergedHead;
while (temp != null) {
System.out.print(temp.value + " ");
temp = temp.next;
}
}
public static Node merge(Node head1, Node head2) {
Node newHead = new Node(-1);
Node temp = newHead;
while (head1 != null && head2 != null) {
if (head1.value < head2.value) {
temp.next = head1; //将head1接到新链表尾部
head1 = head1.next; //head1指针后移
} else if (head1.value > head2.value) {
temp.next = head2; //将head2接到新链表尾部
head2 = head2.next; //head2指针后移
} else {
temp.next = head1; //将head1接到新链表尾部
head1 = head1.next; //head1指针后移
head2 = head2.next; //head2指针后移
}
temp = temp.next; //新链表尾指针后移
}
//将未遍历完的链表接到新链表尾部
if (head1 != null) {
temp.next = head1;
}
if (head2 != null) {
temp.next = head2;
}
return newHead.next;
}
static class Node {
int value;
Node next;
public Node(int value) {
this.value = value;
}
}
}
阅读全文