剑指offer(12)

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

题目一:

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

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

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
/*
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;
    }
}

  接下来给出非递归方式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
/*
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;
    }
}

 

posted @   FigSprite  阅读(200)  评论(0编辑  收藏  举报
努力加载评论中...
点击右上角即可分享
微信分享提示