剑指offer(12)
来两道关于链表链接的题目:
题目一:
输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。
本题要考虑到其中一条链表是空或者两个都是空的情况。
在每个链表安上一个指针,对比一次,提取一个结点,接到目标链表上。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | /* 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 ) return list2; if (list2== null ) return list1; ListNode listMergeHead = null ; ListNode point1 = list1; ListNode point2 = list2; if (point1.val<point2.val){ listMergeHead = point1; listMergeHead.next = Merge(point1.next,point2); } else { listMergeHead = point2; listMergeHead.next = Merge(point1,point2.next); } return listMergeHead; } } |
接下来给出非递归方式
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 | /* 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 ) return list2; if (list2== null ) return list1; ListNode listMergeHead = null ; ListNode current = null ; while (list1!= null &&list2!= null ){ if (list1.val<list2.val){ if (listMergeHead== null ){ listMergeHead=current=list1; } else { current.next=list1; current = current.next; } list1=list1.next; } else { if (listMergeHead== null ){ listMergeHead=current=list2; } else { current.next=list2; current = current.next; } list2=list2.next; } } if (list1== null ){ current.next=list2; } if (list2== null ){ current.next=list1; } return listMergeHead; } } |
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步