leetcode 21. Merge Two Sorted Lists
Posted godlei
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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 together the nodes of the first two lists.
解题分析:
再基础不过的题了,直接看代码吧^-^
具体代码:
1 /** 2 * Definition for singly-linked list. 3 * public class ListNode { 4 * int val; 5 * ListNode next; 6 * ListNode(int x) { val = x; } 7 * } 8 */ 9 public class Solution { 10 public static ListNode mergeTwoLists(ListNode head1, ListNode head2) { 11 if(head1==null) 12 return head2; 13 if(head2==null) 14 return head1; 15 ListNode head=null; 16 ListNode current=null; 17 if(head1.val<=head2.val){ 18 head=head1; 19 head1=head1.next; 20 head.next=null; 21 } 22 else{ 23 head=head2; 24 head2=head2.next; 25 head.next=null; 26 } 27 current=head; 28 while(head1!=null&&head2!=null){ 29 if(head1.val<=head2.val){ 30 current.next=head1; 31 current=current.next; 32 head1=head1.next; 33 current.next=null; 34 } 35 else{ 36 current.next=head2; 37 current=current.next; 38 head2=head2.next; 39 current.next=null; 40 } 41 } 42 if(head1!=null){ 43 current.next=head1; 44 } 45 if(head2!=null){ 46 current.next=head2; 47 } 48 return head; 49 } 50 }
以上是关于leetcode 21. Merge Two Sorted Lists的主要内容,如果未能解决你的问题,请参考以下文章
Leetcode---21. Merge Two Sorted Lists
Leetcode 21. Merge Two Sorted Lists
LeetCode 21. Merge Two Sorted Lists
LeetCode算法-21Merge Two Sorted Lists