将两个有序链表进行合并

来源:互联网 发布:手机淘宝怎么用集分宝 编辑:程序博客网 时间:2024/05/20 04:10
/** * Definition for ListNode. * public class ListNode { *     int val; *     ListNode next; *     ListNode(int val) { *         this.val = val; *         this.next = null; *     } * } */ public class Solution {    /**     * @param ListNode l1 is the head of the linked list     * @param ListNode l2 is the head of the linked list     * @return: ListNode head of linked list     */    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {        ListNode head1,head2,node1,node2;        head1=l1;//        head2=l2;        if(l1==null){            return l2;        }        if(l1.val>l2.val){            head1=l2;//head1用来指向头结点较小的链表            head2=l1;        }        ListNode pre1=head1;        ListNode p;        node1=head1.next;        node2=head2;        while((node1!=null) &&(node2!=null)){            while(node1!=null&&node2.val>node1.val) {                pre1=node1;                node1=node1.next;            }            p=node2.next;            node2.next=node1;            pre1.next=node2;            node2=p;            node1= pre1.next;        }        if((node1==null)&&(node2!=null)){            pre1.next=node2;        }        return head1;            }}

0 0
原创粉丝点击