合并链表
将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
//应该可以用递归的方式去做
if(l1.val>=l2.val){
ListNode curnodeA=l2;
ListNode curnodeB=l1;
ListNode curnodeC;
ListNode curnodeD;
while(true){
if(curnodeB.next==null){
while(curnodeA.next!=null){
curnodeA=curnodeA.next;
}
curnodeA.next=curnodeB;
break;
}
if(curnodeB.val>=curnodeA.val&&curnodeB.val<=curnodeA.next.val){
//插入节点,并将当前结点后移
curnodeC=curnodeB;
curnodeB=curnodeB.next;
curnodeD=curnodeA.next;
curnodeA.next=curnodeC;
curnodeC.next=curnodeD;
}else{
curnodeA=curnodeA.next;
}
}
return l2;
}else{
return mergeTwoLists(l2, l1);
}
}
}
这个算法对于特殊情况可以用!
空间换时间:用一个创造一个新的链表,但是内存还是那几个,按照顺序将各个结点(地址)串联起来!
厉害!
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
ListNode headnode=new ListNode(0);
ListNode curnode=headnode;
while(l1!=null&&l2!=null){
if(l1.val<l2.val){
curnode.next=l1;
curnode=curnode.next;
l1=l1.next;
}else{
curnode.next=l2;
curnode=curnode.next;
l2=l2.next;
}
}
if(l1==null){
curnode.next=l2;
}
if(l2==null){
curnode.next=l1;
}
return headnode.next;
}
}
递归方法
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
//递归方式
if(l1==null){
return l2;
}
if(l2==null){
return l1;
}
if(l1.val<=l2.val){
//会返回排序好的结点
l1.next=mergeTwoLists(l1.next, l2);
return l1;
}else{
l2.next=mergeTwoLists(l1, l2.next);
return l2;
}
}
}