合并两个有序链表 Merge Two Sorted Lists
题目
给定一个只包括 '(',')','{','}','[',']' 的字符串,判断字符串是否有效。
以下为详细说明:
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.
Example:
Input: 1->2->4, 1->3->4
Output: 1->1->2->3->4->4
思路&题解
/**
* 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) {
if (l2 == null) {
return l1;
} else {
return l2;
}
}
if (l2 == null) {
return l1;
}
ListNode result = null;
ListNode top = l1.val < l2.val ? l1 : l2;
while (l1 != null && l2 != null) {
if (l1.val < l2.val) {
if (result == null) {
result = l1;
} else {
result.next = l1;
result = result.next;
}
l1 = l1.next;
} else {
if (result == null) {
result = l2;
} else {
result.next = l2;
result = result.next;
}
l2 = l2.next;
}
}
if (l1 == null) {
result.next = l2;
} else {
result.next = l1;
}
return top;
}
}