22两两交换链表中的结点
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
ListNode* dummyHead = new ListNode();
dummyHead->next = head;
ListNode* cur = dummyHead;
while(cur->next!=nullptr&&cur->next->next!=nullptr){
ListNode* temp = cur->next;
// temp1 = cur->next->next;
ListNode* temp2 = cur->next->next->next;
cur->next = cur->next->next;
cur->next->next = temp;
temp->next = temp2;
cur = temp;
}
return dummyHead->next;
}
};
19.删除链表的倒数第n个结点
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode* dummyHead = new ListNode();
dummyHead->next = head;
ListNode* fast = dummyHead;
ListNode* slow = dummyHead;
while(n && fast->next != nullptr){
fast = fast->next;
n--;
};
while(fast->next != nullptr){
fast = fast->next;
slow = slow->next;
};
ListNode* temp = slow->next;
slow->next = slow->next->next;
delete temp;
return dummyHead->next;
}
};
面试02.07链表相交
class Solution {
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
int sizeA = 0;
int sizeB = 0;
ListNode* curA = headA;
ListNode* curA1 = headA;
ListNode* curB = headB;
ListNode* curB1 = headB;
while(curA != nullptr){
curA = curA->next;
sizeA++;
};
while(curB != nullptr){
curB = curB->next;
sizeB++;
};
if(sizeA>=sizeB){
int a = sizeA - sizeB;
while(a--){
curA1 = curA1->next;
};
while(sizeB--){
if(curA1 == curB1){
return curA1;
};
curA1 = curA1->next;
curB1 = curB1->next;
};
return nullptr;
}else{
int b = sizeB - sizeA;
while(b--){
curB1 = curB1->next;
};
while(sizeB--){
if(curA1 == curB1){
return curA1;
};
curA1 = curA1->next;
curB1 = curB1->next;
};
return nullptr;
}
}
};
142.环形链表(数学推导还是比较难想到的,代码实现不复杂,见代码随想录)
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
ListNode* fast = head;
ListNode* slow = head;
while(fast!=nullptr&&fast->next!=nullptr){
fast = fast->next->next;
slow = slow->next;
if(fast == slow){
ListNode* index1 = fast;
ListNode* index2 = head;
while(index1 != index2){
index1 = index1->next;
index2 = index2->next;
};
return index1;
};
};
return NULL;
}
};