训练营day4
/**
* 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) {
auto dummy = new ListNode(-1);
dummy->next = head;
for(auto p = dummy;p->next && p->next->next;)
{
auto a = p->next,b = p->next->next;
a->next = b->next;
p->next = b;
b->next = a;
p = a;
}
return dummy->next;
}
};
/**
* 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) {
auto dummy = new ListNode(-1);
dummy = head;
int len = 0;
for(auto p = head;p;p = p->next) len++;
if(!head->next) return NULL;
if((len - n ) >= 0 && (len - n ) < len)
{
if(!(len - n ))
{
head = head->next;
dummy = head;
}
else
{
auto p = dummy;
for(int i = 0;i < (len - n - 1);i++) p = p->next;
p->next = p->next->next;
}
}
return dummy;
}
};
/**
* 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) {
auto p = headA,q = headB;
while(p != q)
{
if(p) p = p->next;
else p = headB;
if(q) q = q->next;
else q = headA;
}
return p;
}
};
/**
* 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) {
if(!head || !head->next) return NULL;
//快慢指针,q指针速度为p两倍
auto p = head,q = head->next;
while(q)
{
p = p->next;
q = q->next;
if(!q ) return NULL; //往下指的时候还是要排除空指针情况
q = q->next;
if(p == q)
{
p = head ;
q = q->next;
while(p != q) p = p->next,q = q->next;
return p;
}
}
return NULL;
}
};