24. 两两交换链表中的节点:力扣(LeetCode)官网 - 全球极客挚爱的技术成长平台
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
ListNode* dummyHead = new ListNode(0);
dummyHead->next = head;
ListNode* cur = dummyHead;
while(cur->next!=NULL&&cur->next->next!=NULL){
ListNode* tmp = cur->next;
ListNode* tmp1 = cur->next->next->next;
cur->next = cur->next->next;
cur->next->next = tmp;
cur->next->next->next = tmp1;
cur = cur->next->next;
}
return dummyHead->next;
}
};
这个题如果画图的话就会比较清晰的梳理逻辑了;
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode* dummyHead = new ListNode(0);
dummyHead->next = head;
ListNode* fast = dummyHead;
ListNode* slow = dummyHead;//注意这里是虚头结点而不是头节点
while(n!=0&&fast!=NULL){
fast = fast->next;
n--;
}
fast = fast->next;
while(fast!=NULL){
fast = fast->next;
slow = slow->next;
}
slow->next = slow->next->next;
return dummyHead->next;
}
};
class Solution {
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
ListNode* curA = headA;
ListNode* curB = headB;
int a = 0,b = 0;
int num = 0;
while(curA!=NULL){
a++;
curA = curA->next;
}
while(curB!=NULL){
b++;
curB = curB->next;
}
curA = headA;
curB = headB;
if(a>b){
int c = a-b;
while(c!=0&&curA!=NULL){
curA = curA->next;
c--;
}
}
if(a<b){
int c = b-a;
while(c!=0&&curB!=NULL){
curB = curB->next;
c--;
}
}
while(curA!=NULL&&curB!=NULL){
if(curA != curB){
curA = curA->next;
curB = curB->next;
}
if(curA == curB){
return curA;
}
}
return NULL;
}
};
注意是指针相等而不是结点值相等,搞了半天;
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
ListNode* fast = head;
ListNode* slow = head;
int sut = 0;
while(fast!=NULL&&fast->next!=NULL){
fast = fast->next->next;
slow = slow->next;
if(fast==slow){
sut = 1;
break;
}
}
ListNode* index = head;
int num = 0;
while(index!=slow){
index = index->next;
num++;
slow = slow->next;
}
if(sut == 0){
return NULL;
}
else{
return index;
}
}
};
找环比较简单,定义快慢指针即可,找到入口需要一定数学理解,即从相交点和开头同时出发一个指针,相遇时极为4入口;