1. Add Two Numbers
https://leetcode.com/explore/interview/card/top-interview-questions-medium/107/linked-list/783/
merge lists with carry value:
/*** Definition for singly-linked list.* struct ListNode {* int val;* ListNode *next;* ListNode() : val(0), next(nullptr) {}* ListNode(int x) : val(x), next(nullptr) {}* ListNode(int x, ListNode *next) : val(x), next(next) {}* };*/class Solution {public:ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {ListNode* dummy = new ListNode(-1);ListNode* curr = dummy;int carry = 0;while(l1 || l2){int a = l1 ? l1->val : 0;int b = l2 ? l2->val : 0;curr->next = new ListNode((a + b + carry) % 10);carry = (a + b + carry) / 10; //over 10, carry value is 1l1 = l1 ? l1->next : NULL;l2 = l2 ? l2->next : NULL;curr = curr->next;}if(carry!=0) //if there is a carry value at last, add a new node of 1curr->next = new ListNode(1);return dummy->next;}};
2. Odd Even Linked List
https://www.yuque.com/akiencore/yeyky8/pwh4fl/edit?toc_node_uuid=Ii4DR7VgEcE67yxq
2 lists, one jump from the last node of another one:
//CAUTION: it is talking about the node number and not the value in the nodes
class Solution {
public:
ListNode* oddEvenList(ListNode* head) {
if(!head || !head->next) return head;
ListNode* odd = head;
ListNode* even = head->next;
ListNode* head2 = even;
while(odd->next && even->next){ //if both have next
odd->next = even->next;
odd = odd->next;
even->next = odd->next;
even = even->next;
}
odd->next = head2;
return head;
}
};
3. Intersection of Two Linked Lists
https://leetcode.com/explore/interview/card/top-interview-questions-medium/107/linked-list/785/
“switch”:
/**
* 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) {
ListNode* curr1 = headA;
ListNode* curr2 = headB;
int switched1 = 0;
int switched2 = 0;
while(curr1 && curr2){
if(curr1 == curr2) return curr1;
curr1 = curr1->next;
curr2 = curr2->next;
if(!curr1 && !curr2)
break;
if(!curr1 && switched1 == 0){
curr1 = headB;
switched1 = 1;
} else if(!curr1 && switched1 == 1){
curr1 = headA;
switched1 = 0;
}
if(!curr2 && switched2 == 0){
curr2 = headA;
switched2 = 0;
} else if(!curr2 && switched2 == 1){
curr2 = headB;
switched2 = 1;
}
}
return NULL;
}
};
- To simply explain, this idea is to let 2 curr nodes switch between each other if it meets an end
- and they will meet if they have an intersection, before that, both curr nodes passed the same number of steps

for example,
curr1 from A: 1-9-1-2-4-(null, turn to the head of B)3-2
curr2 from B: 3-2-4-(null, turn to the head of A)1-9-1-2
- if no intersections at all, both nodes reach the end at the same time

for example,
curr 1 from A: 2-6-4-(null, turn to the head of B)1-5-NULL
curr 2 from B: 1-5-(null, turn to the head of A)2-6-4-NULL
