标签:
问题描述: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结果链表的头指针,故应该对头指针进行保存;而如果设置result为null,则需要等待了l1或l2给result赋值才能继续定义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