Combining two sorted linked lists of java programming problems
- 2021-07-01 07:27:02
- OfStack
In this paper, we share the linked list of java merging two sorts for your reference. The specific contents are as follows
/**
*
* Sword finger offer Programming problem ( JAVA Realization ) -No. 1 16 Question: Merging two sorted linked lists
*
* Input two monotonically increasing linked lists, output the linked list after synthesis of two linked lists, Of course, we need the synthesized linked list to satisfy the monotone unabated rule.
*
*/
public class Test16 {
public static ListNode Merge(ListNode list1, ListNode list2) {
if (list1 == null) { // First, judge whether a linked list is empty
return list2;
} else if (list2 == null) {
return list1;
}
ListNode end1 = list1;
ListNode end2 = list2;
ListNode tmp; //end1 And end2 Represent two linked lists respectively, tmp Used for intermediate synthesis linked list
if (end1.val > end2.val) {// Think of a linked list with a small first node as end1
tmp = end1;
end1 = end2;
end2 = tmp;
} else {
}
ListNode newNode = end1;// The first node of the linked list for final return
while (end1.next != null && end2.next != null) { // To link the list 2 Insert elements in the linked list 1 Appropriate position in
if (end1.val <= end2.val && end1.next.val >= end2.val) {
tmp = end2.next;
end2.next = end1.next;
end1.next = end2;
end1 = end2;
end2 = tmp;
} else {
end1 = end1.next;
}
}
if (end1.next == null) {// If linked list 1 When you reach the tail node, you will directly connect the remaining linked list 2 The first node in the
end1.next = end2;
return newNode;
} else {
if (end1.next != null && end2.next == null) {// If linked list 2 When you reach the tail node, you will link the list 2 The last remaining in the 1 Insert nodes into linked list 1
while (end2 != null) {
if (end1.val <= end2.val && end1.next.val >= end2.val) {
end2.next = end1.next;
end1.next = end2;
break;
} else {
end1 = end1.next;
if (end1.next == null) {// Linked list 2 The last node is the largest
end1.next = end2;
break;
}
}
}
}
return newNode;
}
}
public static void main(String[] args) {
ListNode list1 = new ListNode(1);
list1.next = new ListNode(3);
list1.next.next = new ListNode(5);
ListNode list2 = new ListNode(2);
list2.next = new ListNode(4);
list2.next.next = new ListNode(6);
System.out.println(Merge(list2, list1));
}
// Linked list
public static class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}
}