Day 12 胜利属于达瓦里氏!
1 . 剑指 Offer 25. 合并两个排序的链表
思路; 模拟题
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
auto dummy = new ListNode(-1);
dummy -> next = nullptr;
auto cur = dummy;
auto p = l1;
auto q = l2;
while(p && q){
if(p -> val <= q -> val){
cur -> next = p;
p = p -> next;
}else{
cur -> next = q;
q = q -> next;
}
cur = cur -> next;
}
while(p){
cur -> next = p;
p = p -> next;
cur = cur -> next;
}
while(q){
cur -> next = q;
q = q -> next;
cur = cur -> next;
}
return dummy -> next;
}
};
2.剑指 Offer 52. 两个链表的第一个公共节点
思路: 如果这两指针相遇 必然所走的路径长度会相同
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
auto p = headA;
auto q = headB;
while(p != q){
if(p) p = p->next;
else p = headB;
if(q) q = q->next;
else q = headA;
}
return p;
}
};