https://leetcode-cn.com/problems/intersection-of-two-linked-lists/
相交链表
class Solution {
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
if (headA == nullptr || headB == nullptr) {
return nullptr;
}
ListNode *pA = headA, *pB = headB;
while (pA != pB) {
pA = pA == nullptr ? headB : pA->next;
pB = pB == nullptr ? headA : pB->next;
}
return pA;
}
};
删除链表中的元素
https://leetcode-cn.com/problems/remove-linked-list-elements/
/**
* 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* removeElements(ListNode* head, int val) {
ListNode * temp=head;
if(head==nullptr) return head;
while(head!=nullptr&&head->val==val){
head=head->next;
delete(temp);
temp=head;
}
if(head==nullptr) return head;
ListNode * ttemp=head;
temp=head->next;
while(temp!=nullptr){
if(temp->val==val){
ttemp->next=ttemp->next->next;
delete(temp);
temp=ttemp->next;
}else{
ttemp=ttemp->next;
temp=temp->next;
}
}
return head;
}
};
递归有点秀?看起来算法题不用释放内存
class Solution {
public:
ListNode* removeElements(ListNode* head, int val) {
if (head == nullptr) {
return head;
}
head->next = removeElements(head->next, val);
return head->val == val ? head->next : head;
}
};