力扣,https://leetcode.cn/problems/he-bing-liang-ge-pai-xu-de-lian-biao-lcof/description/
1.不增加辅助的头结点
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode trainningPlan(ListNode l1, ListNode l2) {
if (l1 == null) {
return l2;
}
if (l2 == null) {
return l1;
}
ListNode head, cur;
if (l1.val <= l2.val) {
head = l1;
cur = head;
l1 = l1.next;
} else {
head = l2;
cur = head;
l2 = l2.next;
}
while (l1 != null || l2 != null) {
if (l1 == null) {
cur.next = l2;
l2 = l2.next;
} else if (l2 == null) {
cur.next = l1;
l1 = l1.next;
} else if (l1.val <= l2.val) {
cur.next = l1;
l1 = l1.next;
} else if (l1.val > l2.val) {
cur.next = l2;
l2 = l2.next;
}
cur = cur.next;
}
return head;
}
}
2.增加辅助的头结点
class Solution {
public ListNode trainningPlan(ListNode l1, ListNode l2) {
ListNode preHead = new ListNode(-1);
ListNode cur = preHead;
while (l1 != null || l2 != null) {
if (l1 == null) {
cur.next = l2;
break;
} else if (l2 == null) {
cur.next = l1;
break;
} else if (l1.val <= l2.val) {
cur.next = l1;
l1 = l1.next;
} else if (l1.val > l2.val) {
cur.next = l2;
l2 = l2.next;
}
cur = cur.next;
}
return preHead.next;
}
}
Solution1:
不要犯低级错误。。。
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution {
public:
ListNode* Merge(ListNode* pHead1, ListNode* pHead2){
if(pHead1 == NULL)
return pHead2;
else if(pHead2 == NULL)
return pHead1;
else{
struct ListNode* ListMergeHead,*ListMergeTail,*temp1 = pHead1,*temp2 = pHead2;
if(temp1->val <= temp2->val){ //找到头指针
ListMergeHead = temp1;
temp1 = temp1->next;
}
else {
ListMergeHead = temp2;
temp2 = temp2->next;
}
ListMergeTail=ListMergeHead;
while(temp1 != NULL && temp2 != NULL){
if(temp1->val <= temp2->val){
ListMergeTail->next = temp1;
ListMergeTail = ListMergeTail->next;
temp1 = temp1->next;
}
else{
ListMergeTail->next = temp2;
ListMergeTail = ListMergeTail->next;
temp2 = temp2->next;
}
}
if(temp1 == NULL)
ListMergeTail->next = temp2;
else
ListMergeTail->next = temp1;
return ListMergeHead;
}
}
};