Leetcode 21. Merge Two Sorted Lists

来源:互联网 发布:酒店水牌通过网络发送 编辑:程序博客网 时间:2024/05/20 06:09

题目来源:leetcode

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


原创粉丝点击