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.
题意为合并两个有序链表。(这句话意思真是没看太懂,猜着先coding发现就是这个意思)
链表是面试中出现频率非常高的考点,这个题目还可以改进,去掉链表有序条件增加难度,然后就需要进行链表的排序,然后牵扯出快速排序,链表快速排序:http://blog.youkuaiyun.com/huruzun/article/details/25001085
所以链表快速排序又是一个经常问到的问题。(金山网络笔试+面试)
递归求法:
public class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
ListNode Pmerge = null;
if(l1 == null){
return l2;
}
if(l2 == null){
return l1;
}
if(l1.val<l2.val){
Pmerge = l1;
Pmerge.next = mergeTwoLists(l1.next, l2);
}else {
Pmerge = l2;
Pmerge.next = mergeTwoLists(l1, l2.next);
}
return Pmerge;
}
}
非递归求法:采用非递归方法,这个方法不需要利用新的存储空间,只是去改变引用的指向
public class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2){
ListNode Pmerge = null;
if(l1 == null){
return l2;
}
if(l2 == null){
return l1;
}
if(l1.val<l2.val){
Pmerge = l1;
l1 = l1.next;
}
else {
Pmerge = l2;
l2 = l2.next;
}
ListNode head = Pmerge;
while(l1!=null && l2!=null){
if(l1.val<l2.val){
Pmerge.next = l1;
l1 = l1.next;
Pmerge = Pmerge.next;
}else {
Pmerge.next = l2;
l2 = l2.next;
Pmerge = Pmerge.next;
}
}
if(l1 == null){
Pmerge.next = l2;
}else {
Pmerge.next = l1;
}
return head;
}
}