您的位置:首页 > 其它

【leetcode】 21. Merge Two Sorted Lists

2016-07-05 00:29 429 查看

题目描述:

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 static ListNode mergeTwoLists(ListNode head1, ListNode head2) {
if(head1==null)
return head2;
if(head2==null)
return head1;
ListNode head=null;
ListNode current=null;
if(head1.val<=head2.val){
head=head1;
head1=head1.next;
head.next=null;
}
else{
head=head2;
head2=head2.next;
head.next=null;
}
current=head;
while(head1!=null&&head2!=null){
if(head1.val<=head2.val){
current.next=head1;
current=current.next;
head1=head1.next;
current.next=null;
}
else{
current.next=head2;
current=current.next;
head2=head2.next;
current.next=null;
}
}
if(head1!=null){
current.next=head1;
}
if(head2!=null){
current.next=head2;
}
return head;
}
}

 

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: