21. 合并两个有序列表

思路:

由于两个链表本身就是有序的,所以只需要遍历就OK了。

可以设置一个空的头结点,这样可以对两条链表都进行统一的操作,减轻代码量,代码也美观了不少。

 

代码:

 1 /**
 2      * @param {ListNode} list1
 3      * @param {ListNode} list2
 4      * @return {ListNode}
 5      */
 6     var mergeTwoLists = function(list1, list2) {
 7         let head = new ListNode(-1, undefined);
 8         let cur = head;
 9         while(list1 && list2){
10             if(list1.val < list2.val){
11                 cur.next = list1;
12                 list1 = list1.next;
13             }else{
14                 cur.next = list2;
15                 list2 = list2.next;
16             }
17             cur = cur.next;
18         }
19         if(list1){
20             cur.next = list1;
21         }else{
22             cur.next = list2;
23         }
24         return head.next;
25     };

 

posted @ 2022-04-06 18:38  BJFU-VTH  阅读(78)  评论(0编辑  收藏  举报