Merge Two Sorted Lists

来源:互联网 发布:java textarea 滚动条 编辑:程序博客网 时间:2024/05/16 11:07

Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.
将两个已经排好序的链表合并成一个有序链表

/** * Definition for singly-linked list. * public class ListNode { *     int val; *     ListNode next; *     ListNode(int x) { val = x; } * } */class Solution {    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {            if(l1==null&&l2==null){                return null;            }            if(l1==null){                return l2;            }            if(l2==null){                return l1;            }            ListNode head = null;            ListNode p1 = l1;            ListNode p2 = l2;            if(l1.val<l2.val){                head = l1;                p1 = p1.next;            }else{                head =l2;                p2 = p2.next;            }            ListNode p = head;            while(p1!=null&&p2!=null){                if(p1.val<p2.val){                    p.next=p1;                    p1 = p1.next;                    p=p.next;                }else{                    p.next=p2;                    p2 = p2.next;                    p=p.next;                }            }            if(p1==null&&p2!=null){                p.next=p2;            }else if(p1!=null&&p2==null){                p.next=p1;            }else if(p1==null&&p2==null){                return head;            }            return head;    }}

1.首先判断两个链表是否为空,如果都为空 则返回null
2.如果其中一个为空,则直接返回另外一个链表
3.找到新链表的head节点,通过比较两个链表第一个节点的val值确定
4.以此类推,当其中一个链表遍历完成则直接接上另一个链表的剩余值

原创粉丝点击