合并两个排序的链表

来源:互联网 发布:大数据技术案例应用 编辑:程序博客网 时间:2024/06/07 23:10

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

解题思路

先确定头指针,即两个链表中头结点值较小的节点作为头指针,然后通过两个指针分别指向两个链表进行遍历,确定下一个值。将头结点的next指向这个值,移动指向头结点指针即可。

class ListNode {    int val;    ListNode next = null;    ListNode(int val) {        this.val = val;    }}public class hebinglianggepaixudelianbiao {    public ListNode Merge(ListNode list1, ListNode list2) {        if (list1 == null && list2 == null)            return null;        else if (list1 == null)            return list2;        else if (list2 == null)            return list1;        ListNode p1 = list1, p2 = list2;        ListNode head = null;        if (p1.val < p2.val) {            head = p1;            p1 = p1.next;        } else {            head = p2;            p2 = p2.next;        }        ListNode pListNode = head;        while (p1 != null && p2 != null) {            if (p1.val < p2.val) {                ListNode node =p1;                p1 = p1.next;                pListNode.next = node;                pListNode = pListNode.next;            } else {                ListNode node = p2;                p2 = p2.next;                pListNode.next = node;                pListNode = pListNode.next;            }        }        while (p1 != null) {            ListNode node = p1;            p1 = p1.next;            pListNode.next = node;            pListNode = pListNode.next;        }        while (p2 != null) {            ListNode node =p2;            p2 = p2.next;            pListNode.next = node;            pListNode = pListNode.next;        }        return head;    }}
原创粉丝点击