其他分享
首页 > 其他分享> > day12

day12

作者:互联网

1.剑指 Offer 25. 合并两个排序的链表

把l2链合并到l1链上

 1 /**
 2  * Definition for singly-linked list.
 3  * struct ListNode {
 4  *     int val;
 5  *     ListNode *next;
 6  *     ListNode(int x) : val(x), next(NULL) {}
 7  * };
 8  */
 9 class Solution {
10 public:
11     ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
12       if(l1 == nullptr) return l2;
13       if(l2 == nullptr) return l1;
14       if(l1 == nullptr && l2 == nullptr) return l1;
15       if(l1 -> val > l2 -> val) return mergeTwoLists(l2,l1);//这个可以不用递归一下,在l1前面连一个空节点即可
16       ListNode *cur = l1;ListNode* pre;
17       while(l1){
18           if(l2 == nullptr)
19             break;
20           if(l1 -> next == nullptr){               //l1只剩最后一个元素时单独考虑
21               if(l1 -> val <= l2 -> val)
22                   l1 -> next = l2;
23               else{
24                   ListNode* tmp = l2,* pretmp;
25                   while(tmp && l1 -> val > tmp -> val){
26                       pretmp = tmp;
27                       tmp = tmp -> next;
28                   }
29                   pre -> next = l2;
30                   pretmp -> next = l1;
31                   l1 -> next = tmp;
32               }
33               break;
34           }
35           if(l1 -> val > l2 -> val){
36               ListNode* tmp = l2 -> next;
37               l2 -> next = pre -> next;
38               pre -> next = l2;
39               l2 = tmp;
40               pre = pre -> next;
41           }
42           else{
43               pre =  l1;
44               l1 = l1 -> next;
45           }
46       }
47       return cur;
48     }
49 };

还可用创建一条新链,逐个比大小把l1和l2两条链上元素串上去

2.剑指 Offer 52. 两个链表的第一个公共节点

话不多说,去力扣看K神题解叭

 1 /**
 2  * Definition for singly-linked list.
 3  * struct ListNode {
 4  *     int val;
 5  *     ListNode *next;
 6  *     ListNode(int x) : val(x), next(NULL) {}
 7  * };
 8  */
 9 class Solution {
10 public:
11     ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
12         ListNode* A = headA,*B = headB;
13         while(A != B){
14             A = A == nullptr ? headB : A -> next;
15             B = B == nullptr ? headA : B -> next;
16         }
17         return A;
18     }
19 };

 

标签:tmp,ListNode,val,next,l2,day12,l1
来源: https://www.cnblogs.com/balabalabubalabala/p/16460582.html