首页 > 编程语言 > 详细

合并两个排序的链表

时间:2020-09-17 21:36:12      阅读:57      评论:0      收藏:0      [点我收藏+]

输入两个递增排序的链表,合并这两个链表并使新链表中的节点仍然是递增排序的。

示例1:

输入:1->2->4, 1->3->4
输出:1->1->2->3->4->4


class ListNode {
int val;
ListNode next;

ListNode(int x) {
val = x;
}
}



public class
Solution { public static void main(String[] args) { ListNode l1 = new ListNode(1); l1.next = new ListNode(2); l1.next.next = new ListNode(4); ListNode l2 = new ListNode(1); l2.next = new ListNode(3); l2.next.next = new ListNode(4); Solution solution = new Solution(); ListNode listNode = solution.mergeTwoLists(l1, l2); while (listNode!=null){ System.out.println(listNode.val); listNode = listNode.next; } } public ListNode mergeTwoLists(ListNode l1, ListNode l2) { ListNode newHead = new ListNode(-1); ListNode newHeadPoint = newHead; while (l1!=null || l2!=null){ if (l1==null){ newHeadPoint.next = l2; break; } if (l2==null) { newHeadPoint.next = l1; break; } if (l1.val < l2.val){ newHeadPoint.next = l1; newHeadPoint = newHeadPoint.next; l1 = l1.next; continue; } else { newHeadPoint.next = l2; newHeadPoint = newHeadPoint.next; l2 = l2.next; continue; } } return newHead.next; } }

 

合并两个排序的链表

原文:https://www.cnblogs.com/iuyy/p/13687560.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!