题目描述:给你两个递增的链表,合并它们并且合并后的是一个非递减的链表,返回头节点
思路:串针线,首先先判断两个链表是否有null,都不是null的话,设置current1和current2代表两个链表的头,pre1,pre2代表current的前一个节点,初始为null,设置tmp1,tmp2为current的下一个节点,好让串线后的current向下一个节点移动。循环结束,若有个链表不为空,则接到后面。
java程序:
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}*/
public class Solution {
public ListNode Merge(ListNode list1,ListNode list2) {
if(list1==null)
return list2;
if(list2==null)
return list1;
ListNode res = null;
ListNode current1 = list1;
ListNode current2 = list2;
ListNode tmp1 = null;
ListNode tmp2 = null;
ListNode pre1 = null;
ListNode pre2 = null;
if(current1.val<current2.val){
res = current1;
}else{
res = current2;
}
while(current1!=null&¤t2!=null){
if(current1.val<current2.val){
pre1 = current1;
tmp1 = current1.next;
current1.next = current2;
current1 = tmp1;
}else{
pre2 = current2;
tmp2 = current2.next;
current2.next = current1;
current2 = tmp2;
}
}
if(current1!=null){
pre2.next = current1;
}
if(current2!=null){
pre1.next = current2;
}
return res;
}
}