共計 1223 個字符,預計需要花費 4 分鐘才能閱讀完成。
本篇內容介紹了“Java 怎么實現兩個鏈表”的有關知識,在實際案例的操作過程中,不少人都會遇到這樣的困境,接下來就讓丸趣 TV 小編帶領大家學習一下如何處理這些情況吧!希望大家仔細閱讀,能夠學有所成!
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution { public ListNode mergeTwoLists(ListNode l1, ListNode l2) { if (l1 == null) return l2;
if (l2 == null) return l1;
ListNode head = null;
ListNode end = null;
ListNode first = l1; // 第一個鏈表
ListNode second = l2; // 第二個鏈表
while (first != null second != null){
int tmp1 = first.val;
int tmp2 = second.val;
if (tmp1 = tmp2){ if (head == null){
head = first;
end = head; // head 作為頭指針,end 作為操作指針 ***
} else {
end.next = first; // 賦值給操作指針
end = end.next; // 將操作指針的下一個節點賦值給當前節點, 用于循環
}
first = first.next;
} else { if (head == null){
head = second; //head 只作返回結果用
end = head; // head 作為頭指針,end 作為操作指針 ***
} else {
end.next = second; // ?
end = end.next; // ?
}
second = second.next;
}
}
if (first == null){ while (second != null){
end.next = second;
end = end.next;
second = second.next;
}
}
if (second == null){ while (first != null){
end.next = first;
end = end.next;
first = first.next;
}
}
return head;
}
}
“Java 怎么實現兩個鏈表”的內容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業相關的知識可以關注丸趣 TV 網站,丸趣 TV 小編將為大家輸出更多高質量的實用文章!
正文完