您的位置:首页 > Web前端

牛客网-剑指offer-16-合并两个升序链表

2017-09-13 21:27 369 查看
时间限制:1秒 空间限制:32768K 热度指数:157895
本题知识点: 链表
 算法知识视频讲解


题目描述

输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。
/*
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 head = null, tail = null;

        ListNode p1 = list1, p2 = list2;

        while (p1 != null && p2 != null) {

            ListNode temp1 = null, temp2 = null;

            if (p1.val > p2.val) {

                temp1 = p2;

                p2 = p2.next;

            } else if (p1.val < p2.val) {

                temp1 = p1;

                p1 = p1.next;

            } else {

                temp1 = p1;

                temp2 = p2;

                p1 = p1.next;

                p2 = p2.next;

            }

            if (head == null) {

                head = temp1;

                tail = temp1;

            } else {

                tail.next = temp1;

                tail = temp1;

            }

            if (temp2 != null) {

                tail.next = temp2;

                tail = temp2;

            }

        }

        while (p1 != null) {

            tail.next = p1;

            tail = p1;

            p1 = p1.next;

        }

        while (p2 != null) {

            tail.next = p2;

            tail = p2;

            p2 = p2.next;

        }

        return head;

    }

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  算法 链表