Merge Two Sorted Lists


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.
题意:把两个有序的链表合并成一个有序链表

思路:归并排序的归并部分,两个指针指向链表的头节点,比较元素大小,把小的先加入结果链表,而且该指针后移。若是其中一个链表到达尾部,则将另外一个链表的剩余部分复制到结果链表

实现:
/**
 * Definition for singly - linked list.
 * public class ListNode {
 *     int val ;
 *     ListNode next;
 *     ListNode( int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
      public ListNode mergeTwoLists(ListNode l1, ListNode l2 ) {
           ListNode first= new ListNode(0);//结果链表
           ListNode l= first;
           while (l1 != null|| l2!= null){
              
               ListNode t= new ListNode(0);
               if (l1 == null){ //若是l1链表到结尾,则把另外一个链表以此复制到结果链表
                    t.val= l2.val;
                    l2= l2.next;
              }
               else if (l2 == null){ //若是l2链表到结尾,则把另外一个链表以此复制到结果链表
                    t.val= l1.val;
                    l1= l1.next;
              }
               else if (l1 .val<l2 .val){//把两个指针对应的值小的元素的节点加入结果链表
                    t.val= l1.val;
                    l1= l1.next;
              }
               else { //把两个指针对应的值小的元素的节点加入结果链表
                    t.val= l2.val;
                    l2= l2.next;
              }
               l.next= t;
               l= t;
          }
           return first .next;
     }
}
相关文章
相关标签/搜索