Description:
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 {
static public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
ListNode head, p1 = l1, p2 = l2, phead;
if (l1 == null)
return l2;
else if (l2 == null)
return l1;
if (l1.val < l2.val) {
head = p1;
p1 = p1.next;
} else {
head = l2;
p2= p2.next;
}
phead = head;
while (p1 != null && p2 != null) {
if (p1.val < p2.val) {
phead.next = p1;
p1 = p1.next;
} else {
phead.next = p2;
p2 = p2.next;
}
phead=phead.next;
}
while (p1 != null) {
phead.next = p1;
p1 = p1.next;
phead=phead.next;
}
while (p2 != null) {
phead.next = p2;
p2 = p2.next;
phead=phead.next;
}
phead.next=null;
return head;
}
}
运行结果:
代码优化: 参考
1.我的代码是直接返回head因此在while循环之前有一个建立head的过程,同时还有一个判别两个链表是否是null的过程:
但是可以考虑直接返回head.next,这样就省掉判别head,同时省掉判别两个链表是不是null:
2.在两个链表中的某一个已经遍历完之后,我的操作是继续使用指针phead录下去:
但是使用条件运算会更加简洁些: