?LeetCode刷題實(shí)戰(zhàn)21:合并兩個(gè)有序鏈表
算法的重要性,我就不多說了吧,想去大廠,就必須要經(jīng)過基礎(chǔ)知識和業(yè)務(wù)邏輯面試+算法面試。所以,為了提高大家的算法能力,這個(gè)公眾號后續(xù)每天帶大家做一道算法題,題目就從LeetCode上面選 !
今天和大家聊的問題叫做合并兩個(gè)有序鏈表,我們先來看題面:
https://leetcode-cn.com/problems/merge-two-sorted-lists/
Merge two sorted linked lists and return it as a new sorted list. The new list should be made by splicing together the nodes of the first two lists.
題意
樣例
輸入:1->2->4, 1->3->4
輸出:1->1->2->3->4->4
題解
/**
?* Definition for singly-linked list.
?* public class ListNode {
?* int val;//當(dāng)前節(jié)點(diǎn)的值
?* ListNode next;//下一個(gè)節(jié)點(diǎn)的引用值
?* ListNode(int x) { val = x; }
?* }
?*/
class?Solution?{
????public?ListNode mergeTwoLists(ListNode l1, ListNode l2) {
????????ListNode temp=new?ListNode(0);
????????ListNode head=temp;//保留頭節(jié)點(diǎn)的引用
????????while(l1!=null&&l2!=null){
???????????if(l1.val???????????{
???????????????temp.next=l1;
???????????????l1=l1.next;
???????????}
???????????else
???????????{
???????????????temp.next=l2;
???????????????l2=l2.next;
???????????}
???????????temp=temp.next;
????????}
????????if(l1==null) temp.next=l2;//l1子序列為空,則直接拼屆l2
????????if(l2==null) temp.next=l1;
????????return?head.next;//返回頭節(jié)點(diǎn)指向的序列
????}
}
上期推文:
LeetCode刷題實(shí)戰(zhàn)1:在數(shù)組上遍歷出花樣
LeetCode刷題實(shí)戰(zhàn)2:用鏈表模擬加法
LeetCode刷題實(shí)戰(zhàn)3:最長不重復(fù)子串
LeetCode刷題實(shí)戰(zhàn)4:兩個(gè)正序數(shù)組的中位數(shù)
LeetCode刷題實(shí)戰(zhàn)5:判斷回文子串
LeetCode刷題實(shí)戰(zhàn)6:Z字形變換
LeetCode刷題實(shí)戰(zhàn)7:整數(shù)反轉(zhuǎn)
LeetCode刷題實(shí)戰(zhàn)8:字符串轉(zhuǎn)換整數(shù)
LeetCode刷題實(shí)戰(zhàn)9:求解回文數(shù)
LeetCode刷題實(shí)戰(zhàn)10:字符串正則匹配
LeetCode刷題實(shí)戰(zhàn)11: 盛最多水的容器
LeetCode刷題實(shí)戰(zhàn)12: 整數(shù)轉(zhuǎn)羅馬數(shù)字
LeetCode刷題實(shí)戰(zhàn)13: 羅馬數(shù)字轉(zhuǎn)整數(shù)
LeetCode刷題實(shí)戰(zhàn)14: 最長公共前綴
LeetCode刷題實(shí)戰(zhàn)15:三數(shù)之和
LeetCode刷題實(shí)戰(zhàn)16: 最接近的三數(shù)之和
LeetCode刷題實(shí)戰(zhàn)17: 電話號碼的字母組合
LeetCode刷題實(shí)戰(zhàn)18: 四數(shù)之和
LeetCode刷題實(shí)戰(zhàn)19:刪除鏈表的倒數(shù)第N個(gè)節(jié)點(diǎn)
LeetCode刷題實(shí)戰(zhàn)20:有效括號
