Leet Code OJ 21. Merge Two Sorted Lists [Difficulty: Easy]
生活随笔
收集整理的這篇文章主要介紹了
Leet Code OJ 21. Merge Two Sorted Lists [Difficulty: Easy]
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題目:
Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.
翻譯:
合并2個已經排序的鏈表,并且返回一個新的鏈表。這個新的鏈表應該由前面提到的2個鏈表的節點所組成。
分析:
注意頭節點的處理,和鏈表結束(next為null)的處理。以下代碼新增了一個頭指針,來把頭節點的處理和普通節點的處理統一了。
代碼:
/*** 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) {ListNode head=new ListNode(0);ListNode currentNode=head;while(true){if(l1==null&&l2==null){break;}else if(l2!=null&&(l1==null||l1.val>l2.val)){currentNode.next=l2;l2=l2.next;}else{currentNode.next=l1;l1=l1.next;}currentNode=currentNode.next;}return head.next;} }總結
以上是生活随笔為你收集整理的Leet Code OJ 21. Merge Two Sorted Lists [Difficulty: Easy]的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Leet Code OJ 206. Re
- 下一篇: Leet Code OJ 83. Rem