欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 编程资源 > 编程问答 >内容正文

编程问答

【LeetCode从零单排】No21.MergeTwoSortedLists

发布时间:2025/4/5 编程问答 25 豆豆
生活随笔 收集整理的这篇文章主要介绍了 【LeetCode从零单排】No21.MergeTwoSortedLists 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

题目

      这道题是链表的简单应用,将两个有序链表合成一个有序链表。        思路是:表一,表二各取两个对象,分别指向current和next,进行交叉比较排序。 Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.

代码

/*** Definition for singly-linked list.* public class ListNode {* int val;* ListNode next;* ListNode(int x) {* val = x;* next = null;* }* }*/ public class Solution {public ListNode mergeTwoLists(ListNode l1, ListNode l2) {//判断三种null情况if(l1==null && l2==null) return l1;if(l1==null && l2!=null) return l2;if(l1!=null && l2==null) return l1;//定义头指针if(l1.val<=l2.val){//分别对l1和l2取当前和下一节点指针ListNode first=l1;ListNode second=l1.next;ListNode l2_temp=l2;ListNode l2_second=l2.next;//l2插向l1while(l2_temp!=null){if(second!=null){if(l2_temp.val>=first.val && l2_temp.val<=second.val){first.next=l2_temp;l2_temp.next=second;first=first.next;second=first.next; //这个try catch是指当l2_second=null时,l2_second.next是空指针,这时已经排序结束,所以returntry{l2_temp=l2_second; l2_second=l2_second.next;}catch (Exception e){return l1;}}else{first=first.next;second=first.next;}}else{first.next=l2_temp;return l1;}}return l1;}else{ListNode first=l2;ListNode second=l2.next;ListNode l1_temp=l1;ListNode l1_second=l1.next;while(l1_temp!=null){if(second!=null){if(l1_temp.val>=first.val && l1_temp.val<=second.val){first.next=l1_temp;l1_temp.next=second;first=first.next;second=first.next; try{l1_temp=l1_second; l1_second=l1_second.next;}catch (Exception e){return l2;}}else{first=first.next;second=first.next;}}else{first.next=l1_temp;return l2;}}return l2;}}}
代码下载:https://github.com/jimenbian/GarvinLeetCode


/********************************

* 本文来自博客  “李博Garvin“

* 转载请标明出处:http://blog.csdn.net/buptgshengod

******************************************/



总结

以上是生活随笔为你收集整理的【LeetCode从零单排】No21.MergeTwoSortedLists的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。