LeetCode之Merge Two Sorted Lists

举报
chenyu 发表于 2021/07/27 01:27:59 2021/07/27
【摘要】 1、题目 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. 合并2个有序链表     2、代码实现 ...

1、题目

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.
合并2个有序链表

 

 


2、代码实现


   
  1. /**
  2. * Definition for singly-linked list.
  3. * public class ListNode {
  4. * int val;
  5. * ListNode next;
  6. * ListNode(int x) { val = x; }
  7. * }
  8. */
  9. class Solution {
  10. public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
  11. if (l1 == null) {
  12. return l2;
  13. }
  14. if (l2 == null) {
  15. return l1;
  16. }
  17. ListNode head = new ListNode(0);
  18. ListNode cur = head;
  19. while (l1 != null && l2 != null) {
  20. if (l1.val <= l2.val) {
  21. //cur.val = l1.val;这样写会爆空指针异常
  22. cur.next = l1;
  23. l1 = l1.next;
  24. } else {
  25. //cur.val = l2.val;这样写会爆空指针异常
  26. cur.next = l2;
  27. // System.out.println(head.val);
  28. l2 = l2.next;
  29. }
  30. cur = cur.next;
  31. }
  32. if (l1 != null) {
  33. cur.next = l1;
  34. } else {
  35. System.out.println("l2 != null");
  36. cur.next = l2;
  37. }
  38. return head.next;
  39. }
  40. }

 
 

文章来源: chenyu.blog.csdn.net,作者:chen.yu,版权归原作者所有,如需转载,请联系作者。

原文链接:chenyu.blog.csdn.net/article/details/77436512

【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。