Merge Two Sorted Lists leetcode java


題目:

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.

 

題解:

這道題是鏈表操作題,題解方法很直觀。

首先,進行邊界條件判斷,如果任一一個表是空表,就返回另外一個表。

然后,對於新表選取第一個node,選擇兩個表表頭最小的那個作為新表表頭,指針后挪。

然后同時遍歷兩個表,進行拼接。

因為表已經是sorted了,最后把沒有遍歷完的表接在新表后面。

由於新表也會指針挪動,這里同時需要fakehead幫助記錄原始表頭。

代碼如下:

 1      public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
 2          if(l1== null)
 3              return l2;
 4          if(l2== null)
 5              return l1;
 6             
 7         ListNode l3;
 8          if(l1.val<l2.val){
 9             l3 = l1;
10             l1 = l1.next;
11         } else{
12             l3 = l2;
13             l2 = l2.next;
14         }
15         
16         ListNode fakehead =  new ListNode(-1);
17         fakehead.next = l3;
18          while(l1!= null&&l2!= null){
19              if(l1.val<l2.val){
20                 l3.next = l1;
21                 l3 = l3.next;
22                 l1 = l1.next;
23             } else{
24                 l3.next = l2;
25                 l3 = l3.next;
26                 l2 = l2.next;
27             }
28         }
29         
30          if(l1!= null)
31             l3.next = l1;
32          if(l2!= null)
33             l3.next = l2;
34          return fakehead.next;
35     }

 

更簡便的方法是,不需要提前選新表表頭。

對於新表聲明兩個表頭,一個是fakehead,一個是會挪動的指針,用於拼接。同時,邊界條件在后面的補拼中頁解決了,所以開頭沒必要做邊界判斷,這樣代碼簡化為:

 1      public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
 2         ListNode fakehead =  new ListNode(-1);
 3         ListNode l3 = fakehead;
 4          while(l1!= null&&l2!= null){
 5              if(l1.val<l2.val){
 6                 l3.next = l1;
 7                 l3 = l3.next;
 8                 l1 = l1.next;
 9             } else{
10                 l3.next = l2;
11                 l3 = l3.next;
12                 l2 = l2.next;
13             }
14         }
15         
16          if(l1!= null)
17             l3.next = l1;
18          if(l2!= null)
19             l3.next = l2;
20          return fakehead.next;
21     }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM