首页 > 编程语言 > 详细

Java [leetcode 21]Merge Two Sorted Lists

时间:2015-05-10 21:53:49      阅读:243      评论:0      收藏:0      [点我收藏+]

题目描述:

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.

解题思路:

题目的意思是将两个有序链表合成一个有序链表。

逐个比较加入到新的链表即可。

代码如下:

public static ListNode mergeTwoLists(ListNode l1, ListNode l2) {
		ListNode list = new ListNode(0);
		ListNode tmp = list;
		while (l1 != null || l2 != null) {
			if (l1 == null) {
				tmp.next = new ListNode(l2.val);
				l2 = l2.next;
			} else if (l2 == null) {
				tmp.next = new ListNode(l1.val);
				l1 = l1.next;
			} else {
				if (l1.val < l2.val) {
					tmp.next = new ListNode(l1.val);
					l1 = l1.next;
				} else {
					tmp.next = new ListNode(l2.val);
					l2 = l2.next;
				}
			}
			tmp = tmp.next;
		}
		return list.next;
	}

 


 

Java [leetcode 21]Merge Two Sorted Lists

原文:http://www.cnblogs.com/zihaowang/p/4492969.html

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