题目描述
输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。
直接上代码:
package cn.yzx.nowcoder;
/**
* 题目描述
* 输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。
*
* @author yzx
*
*/
public class MergeListNode {
public static void main(String[] args) {
ListNode head1 = new ListNode(1);
ListNode testList = new ListNode(3);
ListNode testList1 = new ListNode(5);
head1.next = testList;
testList.next = testList1;
ListNode head2 = new ListNode(2);
ListNode testList0 = new ListNode(4);
ListNode testList01 = new ListNode(6);
head2.next = testList0;
testList0.next = testList01;
ListNode res = MergeListNode.Merge1(head1, head2);
while (res != null) {
System.out.print(res.val + " ");
res = res.next;
}
}
public static class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}
// 递归
public static ListNode Merge(ListNode list1, ListNode list2) {
if (list1 == null)
return list2;
else if (list2 == null)
return list1;
ListNode resNode = null;
if (list1.val < list2.val) {
resNode = list1;
resNode.next = Merge(list1.next, list2);
} else {
resNode = list2;
resNode.next = Merge(list1, list2.next);
}
return resNode;
}
// 非递归
public static ListNode Merge1(ListNode list1, ListNode list2) {
ListNode result = null;
ListNode current = null;
if (list1 == null)
return list2;
else if (list2 == null)
return list1;
while (list1 != null && list2 != null) {
if (list1.val <= list2.val) {
if (result == null) {
current = result = list1;
} else {
current.next = list1;
current = current.next;
}
list1 = list1.next;
} else {
if (result == null) {
current = result = list2;
} else {
current.next = list2;
current = current.next;
}
list2 = list2.next;
}
}
if(list1 == null){
current.next = list2;
}
if (list2 == null) {
current.next = list1;
}
return result;
}
// 我突然脑袋短路的方法
public static ListNode Merge2(ListNode list1, ListNode list2) {
if (list1 == null)
return list2;
else if (list2 == null)
return list1;
else {
ListNode resNode = null;
if (list1.val <= list2.val) {
resNode = list1;
while (list1 != null || list2 != null) {
if (list1 == null) {
list1.next = list2;
return resNode;
} else if (list2 == null) {
return resNode;
} else {
if (list1.next != null) {
if (list1.val <= list2.val
&& list1.next.val > list2.val) {
ListNode tmp = list2;
list2 = list2.next;
tmp.next = list1.next;
list1.next = tmp;
list1 = tmp;
}
list1 = list1.next;
} else {
list1.next = list2;
return resNode;
}
}
}
return resNode;
} else {
resNode = list2;
while (list2 != null || list1 != null) {
if (list2 == null) {
list2.next = list1;
return resNode;
} else if (list1 == null) {
return resNode;
} else {
if (list2.next != null) {
if (list2.val <= list1.val
&& list2.next.val > list1.val) {
ListNode tmp = list1;
list1 = list1.next;
tmp.next = list2.next;
list2.next = tmp;
list2 = tmp;
}
list2 = list2.next;
} else {
list2.next = list1;
return resNode;
}
}
}
return resNode;
}
}
}
}