Merge Two Sorted Lists (Java)

来源:互联网 发布:cms监控软件安卓手机版 编辑:程序博客网 时间:2024/05/29 17:23

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.

创建listnode节点数值为1 用 Listnode l = new Listnode(1);

Source

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


0 0
原创粉丝点击