标题:
Leetcode - Merge Two Sorted Lists
[打印本页]
作者:
look_w
时间:
2019-2-18 19:34
标题:
Leetcode - Merge Two Sorted Lists
My code:
/**
* 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) {
if (l1 == null && l2 != null)
return l2;
else if (l1 != null && l2 == null)
return l1;
else if (l1 == null && l2 == null)
return null;
ListNode temp1 = l1;
ListNode temp2 = l2;
ListNode head = null;
if (l1.val <= l2.val) {
head = l1;
temp1 = l1.next;
}
else {
head = l2;
temp2 = l2.next;
}
ListNode temp = head;
ListNode tail = temp;
while (temp1 != null && temp2 != null) {
if (temp1.val <= temp2.val) {
temp.next = temp1;
temp = temp.next;
if (temp1.next == null)
tail = temp1;
temp1 = temp1.next;
}
else {
temp.next = temp2;
temp = temp.next;
if (temp2.next == null)
tail = temp2;
temp2 = temp2.next;
}
}
if (temp1 == null)
tail.next = temp2;
else if (temp2 == null)
tail.next = temp1;
return head;
}
}
欢迎光临 电子技术论坛_中国专业的电子工程师学习交流社区-中电网技术论坛 (http://bbs.eccn.com/)
Powered by Discuz! 7.0.0