24.模板代码,可以解决基本上各种反转链表
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
ListNode* node=head;
for(int i=0;i<2;++i){
if(node==nullptr){
return head;
}
node=node->next;
}
ListNode* res=reverseLaR(head,node);
head->next=swapPairs(node);
return res;
}
private:
ListNode* reverseLaR(ListNode* left,ListNode* right){
ListNode* pre=right;
while(left!=right){
ListNode* tmp=left->next;
left->next=pre;
pre=left;
left=tmp;
}
return pre;
}
};
19.两个指针,用虚拟头点
/**
* 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 dummyHead(0,head);
ListNode* fast=&dummyHead;
ListNode* slow=&dummyHead;
while(n--){
fast=fast->next;
}
while(fast->next!=nullptr){
fast=fast->next;
slow=slow->next;
}
slow->next=slow->next->next;
return dummyHead.next;
}
};
面试题 02.07。个人感觉起一个unordered_set的数据结构会好解很多
/**
* 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) {
unordered_set<ListNode*> set;
ListNode* curA=headA;
while(curA!=nullptr){
set.insert(curA);
curA=curA->next;
}
ListNode* curB=headB;
while(curB!=nullptr){
if(set.find(curB)!=set.end()){
return curB;
}
curB=curB->next;
}
return nullptr;
}
};
不用数据结构的解法,就是遍历,记录两个链表大小,大的那个向前走一点,然后开始两个一起遍历。
142.环形链表,同样起个数据结构会简单太多
/**
* 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) {
unordered_set<ListNode*> unorSet;
ListNode* cur=head;
while(cur!=nullptr){
if(unorSet.find(cur)!=unorSet.end()){
return cur;
}
unorSet.insert(cur);
cur=cur->next;
}
return nullptr;
}
};