我正在合并兩個排序的單鏈整數串列。每個節點都有一個值,以及下一個節點的參考。撰寫的代碼是功能性的,并且已經通過了所有相關的測驗用例。
當 head3 節點從不更新時,它如何指向已排序的合并單鏈表中的下一個正確節點?
static SinglyLinkedListNode mergeLists(SinglyLinkedListNode head1, SinglyLinkedListNode head2) {
if (head1 == null) return head2;
if (head2 == null) return head1;
SinglyLinkedListNode head3 = null;
if(head1.data < head2.data){
head3 = head1;
head1 = head1.next;
} else{
head3 = head2;
head2 = head2.next;
}
SinglyLinkedListNode current_node = head3;
while(head1 != null && head2 != null){
if(head1.data < head2.data){
current_node.next = head1;
head1 = head1.next;
} else{
current_node.next = head2;
head2 = head2.next;
}
current_node = current_node.next;
}
if(head1 == null){
current_node.next = head2;
} else {
current_node.next = head1;
}
return head3;
}
Current_node 被宣告并分配了與 head3 相同的下一個節點的值和參考。但是,在接下來的 while 回圈中,根據比較陳述句更新下一個節點的參考 (current_node.next)。head3 永遠不會更新,并且仍然具有它在初始 if else 陳述句 (head3.next) 中的下一個節點參考。
當 head3 回傳時,它應該指向合并排序單鏈表中的下一個節點,但這個參考永遠不會改變。為什么?
uj5u.com熱心網友回復:
head3在開始時初始化一次,是head1或的副本head2。current_node然后用于將節點附加到以 . 開頭的串列中head3。在鏈接串列中嘗試不同的資料值,以便有時head1.data < head2.data有時head1.data > head2.data為了查看 head3 在合并后并不總是相同。
對于要用于穩定合并排序的正確合并,比較應該是head1.data <= head2.data.
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/454256.html
上一篇:了解陣列和指標之間的關系
