(java)Merge Two Sorted Lists

原创 2015年11月18日 18:31:15

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.

思路:首先创建一个空链表l3,如果比较l1和l2的大小,如果l1.val>l2.val,则将l2,链接到l3上,将l2向后移一个,否则就相反

代码如下(已通过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;
   }
}

LeetCode 21 Merge Two Sorted Lists (C,C++,Java,Python)

Problem: Merge two sorted linked lists and return it as a new list. The new list should be made by ...

java: Merge-two-sorted-lists

【问题描述】: Merge two sorted linked lists and return it as a new list. The new list should be made by ...

leetCode 21.Merge Two Sorted Lists (合并排序链表) 解题思路和方法

Merge Two Sorted Lists  Merge two sorted linked lists and return it as a new list. The new list sho...

Leetcode刷题记——21. Merge Two Sorted Lists(合并两有序链表)

一、题目叙述: Merge two sorted linked lists and return it as a new list. The new list should be...

第六周算法分析与设计Ⅱ:Merge Two Sorted Lists

问题描述: Merge two sorted linked lists and return it as a new list. The new list should be made by sp...

LeetCode - Merge Two Sorted Lists

题注 这题本身不难,但是有很多细节的地方需要考虑。我感觉还是因为自己对于链表本身的操作不熟练,导致好几次上传都没有被accept。还是需要继续练习啊! 题目 Merge two sorted lin...

LeetCode笔记:21. Merge Two Sorted Lists

合并两个有序链表

Merge Two Sorted Lists(合并两个有序链表)

Merge two sorted linked lists and return it as a new list. The new list should be made by splicing t...

LeetCode021 Merge Two Sorted Lists

详细见:leetcode.com/problems/merge-two-sorted-lists Java Solution: github package leetcode; im...
  • zxwtry
  • zxwtry
  • 2017年03月30日 11:21
  • 123

21. Merge Two Sorted Lists★

题目内容:Merge two sorted linked lists and return it as a new list. The new list should be made by splic...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:(java)Merge Two Sorted Lists
举报原因:
原因补充:

(最多只允许输入30个字)