|
| 1 | +packagecom.yeahqing.easy._021; |
| 2 | + |
| 3 | +importcom.yeahqing.structure.ListNode; |
| 4 | + |
| 5 | +/** |
| 6 | + * @FileName LeetCode021.java |
| 7 | + * @Desc java-leetcode created by YeahQing |
| 8 | + * @Author YeahQing |
| 9 | + * @Date 2022/10/28 6:42 |
| 10 | + */ |
| 11 | + |
| 12 | +publicclassLeetCode021 { |
| 13 | +publicstaticvoidmain(String[]args) { |
| 14 | +Solutionsolution =newSolution(); |
| 15 | +ListNodel1 =newListNode(); |
| 16 | +ListNodel2 =newListNode(); |
| 17 | +ListNoderet =solution.mergeTwoLists(l1,l2); |
| 18 | +System.out.println(ret.val); |
| 19 | + } |
| 20 | +} |
| 21 | + |
| 22 | +/** |
| 23 | + * <p>Definition for singly-linked list.</p> |
| 24 | + * public class ListNode { |
| 25 | + * int val; |
| 26 | + * ListNode next; |
| 27 | + * ListNode() {} |
| 28 | + * ListNode(int val) { this.val = val; } |
| 29 | + * ListNode(int val, ListNode next) { this.val = val; this.next = next; } |
| 30 | + * } |
| 31 | + */ |
| 32 | +classSolution { |
| 33 | +/** |
| 34 | + * 递归解法 |
| 35 | + * |
| 36 | + * @param list1 有序链表1 |
| 37 | + * @param list2 有序链表2 |
| 38 | + * @return 合并后的链表头节点 |
| 39 | + */ |
| 40 | +publicListNodemergeTwoLists(ListNodelist1,ListNodelist2) { |
| 41 | +if (list1 ==null) { |
| 42 | +returnlist2; |
| 43 | + }elseif (list2 ==null) { |
| 44 | +returnlist1; |
| 45 | + } |
| 46 | +if (list1.val <list2.val) { |
| 47 | +list1.next =mergeTwoLists(list1.next,list2); |
| 48 | +returnlist1; |
| 49 | + } |
| 50 | +list2.next =mergeTwoLists(list1,list2.next); |
| 51 | +returnlist2; |
| 52 | + } |
| 53 | +} |
| 54 | + |
| 55 | +classSolution1extendsSolution { |
| 56 | +/** |
| 57 | + * 迭代解法 |
| 58 | + * |
| 59 | + * @param list1 有序链表1 |
| 60 | + * @param list2 有序链表2 |
| 61 | + * @return 合并后的链表头节点 |
| 62 | + */ |
| 63 | +publicListNodemergeTwoLists(ListNodelist1,ListNodelist2) { |
| 64 | +ListNodepreHead =newListNode(-1); |
| 65 | +ListNodepre =preHead; |
| 66 | +while (list1 !=null &&list2 !=null) { |
| 67 | +if (list1.val <list2.val) { |
| 68 | +pre.next =list1; |
| 69 | +list1 =list1.next; |
| 70 | + }else { |
| 71 | +pre.next =list2; |
| 72 | +list2 =list2.next; |
| 73 | + } |
| 74 | +pre =pre.next; |
| 75 | + } |
| 76 | +pre.next =list1 !=null ?list1 :list2; |
| 77 | +returnpreHead.next; |
| 78 | + } |
| 79 | +} |
| 80 | + |
| 81 | + |