题解 | #链表合并#

链表合并

http://www.nowcoder.com/practice/46bda7f0570a47b6b54a29a0a6ae4c27

import java.util.*; class ListNode{ int val; ListNode next; public ListNode(int val){ this.val =val; } } public class Main{ public static void main(String[] args){ Scanner sc = new Scanner(System.in); ListNode list1 = createList(sc.nextLine().split(" ")); ListNode list2 =createList(sc.nextLine().split(" ")); ListNode dummy = new ListNode(-1); ListNode res = dummy;

    while(list1 != null & list2 != null) {
        if(list1.val > list2.val) {
            dummy.next = list2;
            list2 = list2.next;
            dummy = dummy.next;
        } else if(list1.val <= list2.val) {
            dummy.next = list1;
            list1 = list1.next;
            dummy = dummy.next;
        }
    }
    
    if(list1 != null) {
        dummy.next = list1;
    }
    if(list2 != null) {
        dummy.next = list2;
    }
    res =res.next;
    while(res!=null){
        System.out.print(res.val+" ");
        res=res.next;
    }
}
public static ListNode createList(String[] str){
    if(str==null||str.length==0){
        return null;
    }
    ListNode pre = new ListNode(0);
    ListNode list = pre;
    for(int i=0;i<str.length;i++){
        list.next = new ListNode(Integer.parseInt(str[i]));
        list = list.next;
    }
    return pre.next;
}

}

全部评论

相关推荐

11-24 19:04
已编辑
湖南工商大学 Java
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务