标签:输出 i+1 list 合成 int system return || 输入
题目描述
输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。
1 public static ListNode Merge(ListNode list1,ListNode list2) { 2 if(list1==null||list2==null){ 3 if(list1==null){ 4 return list2; 5 }else{ 6 return list1; 7 } 8 } 9 ArrayList<ListNode> res = new ArrayList<>(); 10 while (list1!=null&&list2!=null){ 11 if(list1.val<=list2.val){ 12 res.add(new ListNode(list1.val)); 13 list1=list1.next; 14 }else{ 15 res.add(new ListNode(list2.val)); 16 list2=list2.next; 17 } 18 } 19 while(list1!=null){ 20 res.add(new ListNode(list1.val)); 21 list1=list1.next; 22 } 23 while (list2!=null){ 24 res.add(new ListNode(list2.val)); 25 list2=list2.next; 26 } 27 //建立节点间的next联系 28 for(int i = 0;i<res.size()-1;i++){ 29 res.get(i).next = res.get(i+1); 30 } 31 return res.get(0); 32 }
1 public static ListNode Merge01(ListNode list1,ListNode list2) { 2 ListNode newHead = new ListNode(-1); 3 ListNode current = newHead; 4 while (list1 != null && list2 != null) { 5 if (list1.val < list2.val) { 6 current.next = list1; 7 list1 = list1.next; 8 } else { 9 current.next = list2; 10 list2 = list2.next; 11 } 12 current = current.next; 13 } 14 if (list1 != null){ 15 current.next = list1; 16 } 17 if (list2 != null) { 18 current.next = list2; 19 } 20 return newHead.next; 21 }
1 public ListNode Merge02(ListNode list1,ListNode list2) { 2 if (list1 == null) { 3 return list2; 4 } 5 if (list2 == null) { 6 return list1; 7 } 8 if (list1.val < list2.val) { 9 list1.next = Merge(list1.next, list2); 10 return list1; 11 } else { 12 list2.next = Merge(list1, list2.next); 13 return list2; 14 } 15 }
初始化链表:
1 public static class ListNode { 2 int val; 3 ListNode next = null; 4 ListNode(int val) { 5 this.val = val; 6 } 7 } 8 public static ListNode createList(int[] list){ 9 ListNode head = new ListNode(-1); 10 ListNode current=head; 11 for(int i=0;i<list.length;i++){ 12 current.next=new ListNode(list[i]); 13 current=current.next; 14 } 15 return head.next; 16 }
测试:
1 public static void main(String[] args) { 2 int[] list1={1,3,5}; 3 int[] list2={2,4,6}; 4 ListNode root1 = createList(list1); 5 ListNode root2 = createList(list2); 6 ListNode merge = Merge(root1, root2); 7 while (merge!=null){ 8 System.out.print(merge.val+" "); 9 merge=merge.next; 10 } 11 } 12 输出:1 2 3 4 5 6
标签:输出 i+1 list 合成 int system return || 输入
原文地址:https://www.cnblogs.com/Blog-cpc/p/12392058.html