题解 | #合并两个排序的链表#

合并两个排序的链表

http://www.nowcoder.com/practice/d8b6b4358f774294a89de2a6ac4d9337

合并排序的变形,简单题

/*
public class ListNode {
    int val;
    ListNode next = null;

    ListNode(int val) {
        this.val = val;
    }
}*/
public class Solution {
    public ListNode Merge(ListNode list1,ListNode list2) {
        ListNode head = null;
        ListNode p = head;
        while(list1 != null && list2 != null) {
            ListNode node = null;
            if (list1.val < list2.val) {
                node = list1;
                list1 = list1.next;
            } else {
                node = list2;
                list2 = list2.next;
            }
            if (head == null) {
                head = node;
                p = head;
            } else {
                p.next = node;
                p = p.next;
            }
            node.next = null;
        }
        while(list1 != null) {
            ListNode node = list1;
            if (head == null) {
                head = node;
                p = head;
            } else {
                p.next = node;
                p = p.next;
            }
            list1 = list1.next;
            node.next = null;
        }
        while(list2 != null) {
            ListNode node = list2;
            if (head == null) {
                head = node;
                p = head;
            } else {
                p.next = node;
                p = p.next;
            }
            list2 = list2.next;
            node.next = null;
        }
        return head;
    }
}
全部评论

相关推荐

宇算唯航:目测实缴资本不超100W的小公司
点赞 评论 收藏
分享
不要停下啊:大二打开牛客,你有机会开卷了,卷起来,去找课程学习,在牛客上看看大家面试笔试都需要会什么,岗位有什么需求就去学什么,努力的人就一定会有收获,这句话从来都经得起考验,像我现在大三了啥也不会,被迫强行考研,炼狱难度开局,啥也不会,找工作没希望了,考研有丝丝机会
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务