剑指offer(12)

时间:2024-09-04 15:36:08

来两道关于链表链接的题目:

题目一:

  输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。

  本题要考虑到其中一条链表是空或者两个都是空的情况。

  在每个链表安上一个指针,对比一次,提取一个结点,接到目标链表上。

/*
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 listMergeHead = null;
ListNode point1 = list1;
ListNode point2 = list2; if(point1.val<point2.val){
listMergeHead = point1;
listMergeHead.next = Merge(point1.next,point2);
}else{
listMergeHead = point2;
listMergeHead.next = Merge(point1,point2.next);
} return listMergeHead;
}
}

  接下来给出非递归方式

/*
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 listMergeHead = null;
ListNode current = null; while(list1!=null&&list2!=null){
if(list1.val<list2.val){
if(listMergeHead==null){
listMergeHead=current=list1;
}else{
current.next=list1;
current = current.next;
}
list1=list1.next;
}else{
if(listMergeHead==null){
listMergeHead=current=list2;
}else{
current.next=list2;
current = current.next;
}
list2=list2.next;
}
} if(list1==null){
current.next=list2;
}
if(list2==null){
current.next=list1;
}
return listMergeHead;
}
}