剑指 Offer 25. 合并两个排序的链表(21. 合并两个有序链表)
题目:
思路:
【1】简单思路:如何两个链表是有序的,且要合并,那么情况分为:
1)其中一条链表是空的,返回另外一条 2)两条都不为空: 【1】当两条都存在数据时,要进行比较,然后取小的塞入新链表中。 【2】当一条遍历尽了,那么另一条要自动接上去
代码展示:
简单思路的实现:
//时间0 ms击败100% //内存41.6 MB击败43.94% /** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ class Solution { public ListNode mergeTwoLists(ListNode l1, ListNode l2) { if (l1 == null) return l2; if (l2 == null) return l1; ListNode res = new ListNode(0); ListNode temp = res; while (l1 != null && l2 != null){ if (l1.val > l2.val){ temp.next = l2; l2 = l2.next; }else { temp.next = l1; l1 = l1.next; } temp = temp.next; } while (l1 != null){ temp.next = l1; l1 = l1.next; temp = temp.next; } while (l2 != null){ temp.next = l2; l2 = l2.next; temp = temp.next; } return res.next; } }
对代码部分进行简化:
class Solution { public ListNode mergeTwoLists(ListNode list1, ListNode list2) { ListNode prehead = new ListNode(-1); ListNode curr = prehead; while(list1 != null && list2 != null){ if(list1.val <= list2.val){ curr.next = list1; list1 = list1.next; } else{ curr.next = list2; list2 = list2.next; } curr = curr.next; } curr.next = list1 == null ? list2 : list1; return prehead.next; } }