您的位置:首页 > 编程语言 > Java开发

2.【排序】Merge Two Sorted Lists--Accepted Java code

2016-07-18 18:22 465 查看
leetcode url:https://leetcode.com/problems/merge-two-sorted-lists/

/**
* Definition for singly-linked list.
* public class ListNode {
*     int val;
*     ListNode next;
*     ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
ListNode head=new ListNode(0);
head.next=l1;
ListNode p=head;
ListNode q=l2;
ListNode tmp;
while(p.next!=null && q!=null){
if(p.next.val<=q.val){
p=p.next;
}else{
tmp=q.next;
q.next=p.next;
p.next=q;
p=p.next;
q=tmp;
}
}
if(q!=null){
p.next=q;
}
if(l1==null) return l2;
return head.next;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: