21. Merge Two Sorted Lists

来源:互联网 发布:明星淘宝店哪里找 编辑:程序博客网 时间:2024/06/05 20:25

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.

思路:就是设置一个头结点res,如果list1中的当前节点值比list2中的当前节点值小,就将list1的当前节点链接到res中,否则就将list2的当前节点链接到res中,注意,最后还要将list1和list2中剩下的节点链接到res中

代码如下(已通过leetcode)

public class Solution {
   public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
    if(l1==null) return l2;
    if(l2==null) return l1;
       ListNode p=l1;
       ListNode q=l2;
       ListNode a;
       if(p.val>q.val) {
        a=q;
        q=q.next;
        } else {
        a=p;
        p=p.next;
        }
       ListNode ans=a;
       
       while(p!=null && q!=null) {
        if(p.val>q.val) {
        a.next=q;
        q=q.next;
        a=a.next;
       
        } else {
        a.next=p;
        p=p.next;
        a=a.next;
        }
       }
       while(p!=null) {
        a.next=p;
        p=p.next;
        a=a.next;
       }
       while(q!=null) {
        a.next=q;
        q=q.next;
        a=a.next;
       }
       return ans;
   }
}

0 0
原创粉丝点击