剑指offer(十六)合并两个排序的链表

xiaoxiao2021-02-28  82

题目

输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。

案例

输入{1,3,5},{2,4,6},则应该输出{1,2,3,4,5,6}

分析

两个递增链表,合并成一个单调不减的链表需要从跟节点开始,比较两个链表大小,然后将最小的放入新的链表中,最小链表所在的链表则需要舍弃该节点,然后继续比较

解题代码

/* public class ListNode { int val; ListNode next = null; ListNode(int val) { this.val = val; } }*/ public class Solution { public ListNode Merge(ListNode list1,ListNode list2) { if(list1 == null && list2 == null) return null; ListNode node = null; ListNode newNode = new ListNode(0); boolean flag = true; while(list1 != null || list2 != null){ if(list1 == null) { newNode.next = list2; list2 = null; } else if(list2 == null) { newNode.next = list1; list1 = null; } else if(list1.val < list2.val) { newNode.next = new ListNode(list1.val); list1 = list1.next; } else { newNode.next = new ListNode(list2.val); list2 = list2.next; } if(flag){ node = newNode.next;//引用根节点,然后其余的交给newNode自动补充进来 flag = false; } newNode = newNode.next; } return node; } } 递归:递归方法简洁一点 public ListNode Merge(ListNode list1,ListNode list2) { if(list1 == null){ return list2; } if(list2 == null){ return list1; } if(list1.val <= list2.val){ list1.next = Merge(list1.next, list2); return list1; }else{ list2.next = Merge(list1, list2.next); return list2; } } 总结 对于递归认识不太深刻,不然也应当能想到这种方法,思路还是有点局限
转载请注明原文地址: https://www.6miu.com/read-76825.html

最新回复(0)