剑指Offer第九题:合并两个排序的链表
题目描述
输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。
题目分析
根据题意,我们只要新建一个头结点,再根据其中一个链表遍历另外一个链表,比较他们大小,小得就赋值给这个头结点的next位。
算法分析
- 如果其中一个链表为空,那么返回另外一个链表。
- 如果两个链表都为空,那么返回空。
- 头结点应该比较两个链表的第一位数据,小得那个作为头结点。
- 在遍历过程中,肯定其中一个链表先遍历完成,那么我们将没有遍历完成的链表剩下的部分直接指向就可以了
源代码
1 public class ListNode { 2 int val; 3 ListNode next = null; 4 5 ListNode(int val) { 6 this.val = val; 7 } 8 } 9 public class Solution { 10 public ListNode Merge(ListNode list1,ListNode list2) { 11 if(list1==null) { 12 if(list2==null) 13 return null; 14 return list2; 15 } 16 if(list2==null) { 17 return list1; 18 } 19 ListNode newList=null; 20 ListNode head=null; 21 22 while(list2!=null&&list1!=null) { 23 if(list1.val<=list2.val) { 24 if(head == null){ 25 head = newList = list1; 26 }else{ 27 newList.next=list1; 28 newList=newList.next; 29 } 30 list1=list1.next; 31 }else { 32 33 if(head == null){ 34 head = newList = list2; 35 }else{ 36 newList.next=list2; 37 newList=newList.next; 38 } 39 list2=list2.next; 40 } 41 } 42 if(list1==null) { 43 newList.next=list2; 44 }else 45 newList.next=list1; 46 return head; 47 48 } 49 }