码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode-21 Merge Two Sorted Lists

时间:2015-04-28 09:41:31      阅读:108      评论:0      收藏:0      [点我收藏+]

标签:



问题描述:Merge two sorted linked lists and return it as a new list. The new listshould be made by splicing together the nodes of the first two lists.

问题分析:

算法本身不难,比较两个链表头节点的值,取较小者赋给result

方法结果要返回该result结果链表的头指针,故应该对头指针进行保存;而如果设置resultnull,则需要等待了l1l2result赋值才能继续定义result.next;过于繁琐,故效仿C++中的头前节点,定义一个new ListNode(0),则头结点就是其result.next;

方法二采用递归的方法进行实现;

代码:

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

public class Solution {
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
		ListNode result = new ListNode(0);
		ListNode temp = result;
		
		while((l1 != null) && (l2 != null)){
			if(l1.val <= l2.val){
				temp.next = l1;
				l1 = l1.next;
			}
			else {
				temp.next = l2;
				l2 = l2.next;
			}
		
			temp = temp.next;
		}
		
		if(l1 != null)
			temp.next = l1;
		
		if(l2 != null)
			temp.next = l2;
		
        return result.next;
    }
}


方法二:

public class Solution {
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
    	//注意返回值不要弄错,此其实对应与前面方法最后的相关处理
    	if(l1 == null)  return l2;
    	if(l2 == null)  return l1;
    	
    	ListNode result = null;
    	
    	if(l1.val <= l2.val)
    	{
    		result = l1;
    		result.next = mergeTwoLists(l1.next, l2);
    	}
    	else
        {
	        result = l2;
		result.next = mergeTwoLists(l1, l2.next);
        }
    	
    	return result;
    }
}


leetcode-21 Merge Two Sorted Lists

标签:

原文地址:http://blog.csdn.net/woliuyunyicai/article/details/45330893

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!