[LeetCode]Merge Two Sorted Lists-合并两个有序链表

来源:互联网 发布:电子秤回收数据失败 编辑:程序博客网 时间:2024/05/20 11:49

题目:

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.

思路和注意事项:

这道题很简单。但有几个我犯的错误
  1. 创建一个ListNode类,构造函数一定要有参数int
  2. 创建l3就带来一个问题,l3中声明的内容不在链表中,于是要return l3.next。 这就用到了头节点概念
  3. 这个链表不需要返回头节点

代码:

/** * 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 l3=new ListNode(0);        ListNode p=l3;        while(l1!=null && l2!=null){            if(l1.val<=l2.val){                p.next=l1;                l1=l1.next;            }            else{                p.next=l2;                l2=l2.next;            }            p=p.next;        }        if(l1!=null){            p.next=l1;        }        else if(l2!=null){            p.next=l2;        }        return l3.next;//important!    }}


0 0
原创粉丝点击