21. 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
我的
struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2){
if(!l1 && !l2)return l1;
if(!l1)return l2;
if(!l2)return l1;
struct ListNode *p,*head;
head = l1->val <= l2->val ? l1 : l2;
while(l1 && l2){
if(l1->val > l2->val){
while(l1->val >= l2->val){
p = l2;
l2 = l2->next;
if(!l2)break;
}
p->next = l1;
}
else{
while(l2->val >= l1->val){
p = l1;
l1 = l1->next;
if(!l1)break;
}
p->next = l2;
}
}
return head;
}
别人的
递归
感到深深绝望,简洁!!!
emmm。。。评论说缺点是可能会造成堆栈溢出,因为我们不知道链表的长度。(确实)
public ListNode mergeTwoLists(ListNode l1, ListNode l2){
if(l1 == null) return l2;
if(l2 == null) return l1;
if(l1.val < l2.val){
l1.next = mergeTwoLists(l1.next, l2);
return l1;
} else{
l2.next = mergeTwoLists(l1, l2.next);
return l2;
}
}
这是迭代
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
ListNode head = new ListNode(0);
ListNode handler = head;
while(l1 != null && l2 != null) {
if (l1.val <= l2.val) {
handler.next = l1;
l1 = l1.next;
} else {
handler.next = l2;
l2 = l2.next;
}
handler = handler.next;
}
if (l1 != null) {
handler.next = l1;
} else if (l2 != null) {
handler.next = l2;
}
return head.next;
}
思路
- 再一次觉得自己的逻辑性不是很强,逻辑运算和判断部分老是会走神。
- 因为l1和l2指针会移动,所以我们要有一个指针来抓住合并后的链表并作为返回值。还有提防l1和l2其中有空指针。
- 我们进入循环判断链表节点的大小:假如l2大,那么再进入一个循环判断大小,找到l1中比l2大的节点,同时还要p来抓住l1上一个节点,找到之后把p指向l2。这样就可以把几个逻辑大小的节点连接到一起,而且p抓的是上一个节点,不会不小心就丢掉了剩下的链表,同时还要注意到尾部时造成的空指针(循环会报错)。>=和<=是为了防止遇到相同值的节点而导致p没有抓到节点(开头的情况)。