代码随想录算法训练营第四天|24. 两两交换链表中的节点,19.删除链表的倒数第N个节点,面试题 02.07. 链表相交,142.环形链表II
后两道题没有按照标准答案写,使用了指针数组及其find函数,很爽
24.两两交换链表中的节点
/**
* 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* swapPairs(ListNode* head) {
ListNode* vir_head=new ListNode();
vir_head->next=head;
ListNode* move_point=vir_head;
while(move_point->next!=nullptr&&move_point->next->next!=nullptr){
ListNode* temp_ptr_1=move_point->next;
ListNode* temp_ptr_2=move_point->next->next->next;
move_point->next=move_point->next->next;
move_point->next->next=temp_ptr_1;
move_point->next->next->next=temp_ptr_2;
move_point=move_point->next->next;
}
head=vir_head->next;
delete vir_head;
return head;
}
};
19.删除链表的倒数第N个节点
/**
* 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* removeNthFromEnd(ListNode* head, int n) {
ListNode* vir_head=new ListNode();
vir_head->next=head;
ListNode* move_ptr=vir_head;
int size=0;
while(move_ptr->next!=nullptr){
++size;
move_ptr=move_ptr->next;
}
int num=size-n;
move_ptr=vir_head;
while(num!=0){
move_ptr=move_ptr->next;
--num;
}
move_ptr->next=move_ptr->next->next;
head=vir_head->next;
delete vir_head;
return head;
}
};
面试题 02.07. 链表相交
/**
* 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* vir_head_a=new ListNode;
ListNode* vir_head_b=new ListNode;
vir_head_a->next=headA;
vir_head_b->next=headB;
vector<ListNode*> test={};
while(vir_head_a->next!=nullptr){
vir_head_a=vir_head_a->next;
test.push_back(vir_head_a);
}
while(vir_head_b->next!=nullptr){
vir_head_b=vir_head_b->next;
if(find(test.begin(),test.end(),vir_head_b)!=test.end()){
return vir_head_b;
}
}
return nullptr;
}
};
142.环形链表II
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
ListNode* move_ptr=head;
vector<ListNode*> temp_list={};
while(move_ptr!=nullptr){
temp_list.push_back(move_ptr);
move_ptr=move_ptr->next;
if(find(temp_list.begin(),temp_list.end(),move_ptr)!=temp_list.end()){
return move_ptr;
}
}
return nullptr;
}
};

浙公网安备 33010602011771号