21. Merge Two Sorted Lists

原创 2016年06月01日 18:34:30

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; }
 * }
 */
public class Solution {
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
       ListNode p1 = l1;
       ListNode p2 = l2;
       ListNode presult = new ListNode(0);
       ListNode p = presult;
       
       while(p1 != null && p2 != null){
           if(p1.val >= p2.val){
               p.next = p2;
               p2 = p2.next;
           }else{
               p.next = p1;
               p1 = p1.next;
           }
           p = p.next;
       }
       if(p1 != null){
           p.next = p1;
       }
       if(p2 != null){
           p.next = p2;
       }
       
       return presult.next;
      }
    }


版权声明:本文为博主原创文章,未经博主允许不得转载。

LeetCode笔记:21. Merge Two Sorted Lists

合并两个有序链表

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...

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

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

LeetCode题解-21-Merge Two Sorted Lists

原题 本题较为简单,但是只想到了迭代的解法,没有想到递归。 迭代法 解题思路 比较L1与L2并增加新链表的节点,值为L1或者L2中较小的值。 代码 public c...

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 ...

LeetCode算法题——21. Merge Two Sorted Lists

题目 Merge two sorted linked lists and return it as a new list. The new list should be made by splici...
  • LZTree
  • LZTree
  • 2017年04月12日 17:01
  • 164

21.[Leetcode]Merge Two Sorted Lists

题意:归并两个排好序的链表我的思路;我们没有考虑递归的方法,也没有想到用递归解决,先贴出c++的非递归/** * Definition for singly-linked list. * stru...

leetcode[21 链表]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...

Leetcode21: Merge Two Sorted Lists

还是和链表有关的问题,和第二题比较像,代码如下 # Definition for singly-linked list. # class ListNode(object): # def _...

leetcode 21. Merge Two Sorted Lists

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

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