需要了解sortingPtr Variable是如何更新的。
public class MergeSortedLinkedLists {
public static Node mergeLinkedLists(Node head1, Node head2, Node mergedHead){
Node sortingPtr = null;
if(head1 == null && head2 != null){
return head2;
}
if(head1 == null && head2 == null){
return mergedHead;
}
while(head1 != null && head2 != null){
System.out.println("head1.data - " + head1.data);
System.out.println("head2.data - " + head2.data);
System.out.println("sortingPtr - " + sortingPtr);
/*while(sortingPtr != null){
System.out.print("sortingPtr.data - " + sortingPtr.data + " ");
sortingPtr = sortingPtr.next;
}*/
System.out.println();
if(head1.data < head2.data){
System.out.println("head1 < head2");
if(mergedHead != null){
mergedHead.next = head1;
mergedHead = head1;
} else{
sortingPtr = head1;
mergedHead = head1;
}
head1 = head1.next;
} else{
System.out.println("head2 < head1");
if(mergedHead != null){
mergedHead.next = head2;
mergedHead = head2;
} else{
sortingPtr = head2;
mergedHead = head2;
}
head2 = head2.next;
}
}
if(head1 == null){
mergedHead.next = head2;
}
if(head2 == null){
mergedHead.next = head1;
}
return sortingPtr;
}
public static void main(String[] args) {
SinglyLinkedList linkedList1 = new SinglyLinkedList();
linkedList1.head = linkedList1.new Node(10);
linkedList1.head.next = linkedList1.new Node(50);
linkedList1.head.next.next = linkedList1.new Node(70);
linkedList1.head.next.next.next = linkedList1.new Node(90);
linkedList1.head.next.next.next.next = linkedList1.new Node(100);
SinglyLinkedList linkedList2 = new SinglyLinkedList();
linkedList2.head = linkedList2.new Node(20);
linkedList2.head.next = linkedList2.new Node(30);
linkedList2.head.next.next = linkedList2.new Node(40);
linkedList2.head.next.next.next = linkedList2.new Node(60);
linkedList2.head.next.next.next.next = linkedList2.new Node(80);
SinglyLinkedList mergedList = new SinglyLinkedList();
mergedList.head = null;
mergedList.head = mergeLinkedLists(linkedList1.head, linkedList2.head, mergedList.head);
Node head = mergedList.head;
while(head != null){
System.out.print(head.data + " ");
head = head.next;
}
}
}
class SinglyLinkedList{
Node head;
class Node{
int data;
Node next;
Node(int data){
this.data = data;
next = null;
}
}
}
我正在尝试合并 2 个排序的链表。方法mergeLinkedLists在sortingPtr变量中返回合并列表的头部。但是我想了解 sortingPtr 变量是如何更新以返回上述代码中合并列表的头部的。
else{
sortingPtr = head1;
mergedHead = head1;
}
和
else{
sortingPtr = head2;
mergedHead = head2;
}
这些代码块确保当 mergedHead 为空(即合并过程尚未开始(时,我们将 sortingPtr 的值设置为 mergedHead 的值