class ListNode { int val; ListNode next = null; ListNode(int val) { this.val = val; } } public class MergeTwoList { public ListNode Merge(ListNode list1, ListNode list2) { if (list1 == null) return list2; if (list2 == null) return list1; ListNode mergeList = null; // 如果表1的头结点小于表2头结点,表1的头结点就是新表的头结点 if (list1.val < list2.val) { mergeList = list1; // 递归 mergeList.next = Merge(list1.next, list2); } else { mergeList = list2; mergeList.next = Merge(list1, list2.next); } return mergeList; } void printList(ListNode mergeList) { while (mergeList != null) { System.out.print(mergeList.val + ","); mergeList = mergeList.next; } } public static void main(String[] args) { ListNode list1 = new ListNode(1); list1.next = new ListNode(3); list1.next.next = new ListNode(5); list1.next.next.next = new ListNode(7); // ListNode list2 = null; ListNode list2 = new ListNode(2); list2.next = new ListNode(2); list2.next.next = new ListNode(6); list2.next.next.next = new ListNode(8); MergeTwoList m = new MergeTwoList(); ListNode mergeList = m.Merge(list1, list2); m.printList(mergeList); } }
java实现输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。
最新推荐文章于 2022-03-16 14:19:23 发布