Merge Two Sorted Lists

来源:互联网 发布:阿里云机顶盒刷机工具 编辑:程序博客网 时间:2024/06/01 08:54

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.

题目的意思是给定两个有序链表,归并两个链表,并返回一个新的单链表
注意当两个链表中的数字有相等的时候,新的链表中是有重复的数字的。并且要注意头结点的建立,先建立一个头结点,最后返回的时候只是头结点的next

/** * 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) {         if(l1==null&&l2==null) return null;            ListNode result=new ListNode(-1);            ListNode p=result;            while(l1!=null&&l2!=null)            {                if(l1.val<l2.val)                {                     ListNode node=new ListNode(l1.val);                     p.next=node;                     l1=l1.next;                }                else if(l1.val==l2.val)                {                    ListNode node=new ListNode(l1.val);                    p.next=node;                    p=p.next;                    ListNode node2=new ListNode(l2.val);                    p.next=node2;                    l1=l1.next;                    l2=l2.next;                }                else{                    ListNode node=new ListNode(l2.val);                    p.next=node;                    l2=l2.next;                }                p=p.next;            }           if(l1!=null) p.next=l1;           if(l2!=null) p.next=l2;            return result.next;    }}
0 0
原创粉丝点击