代码随想录day4
24.两两交换链表:注意虚拟头节点的使用
ListNode* swapPairs(ListNode* head) {
ListNode* dummy = new ListNode();
dummy->next = head;
ListNode* current = dummy;
while(current->next != nullptr && current->next->next != nullptr){
ListNode* tmp = current->next;
ListNode* tmp1 = current->next->next->next;
current->next = current->next->next;
current->next->next = tmp;
current->next->next->next = tmp1;
current = current->next->next;
}
return dummy->next;
}
19.删除链表中的倒数第N个结点:注意使用快慢指针,以及中间的间隔n的判断
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode* dummy = new ListNode();
dummy->next = head;
ListNode* fast = dummy;
ListNode* slow = dummy;
//先移动fast指针领先slow n+1 个位置
while(n-- && fast != nullptr){
fast = fast->next;
}
fast = fast->next;
//同时移动fast,slow到fast抵达最后
while(fast != nullptr){
fast = fast->next;
slow = slow->next;
}
//删除第N个需要用到的是第N-1个节点
ListNode* tmp = slow->next;
slow->next = tmp->next;
delete(tmp);
return dummy->next;
}
面试题02.07链表相交://理解链表相交不是值相等,而是指向同一块区域
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
ListNode* listA = headA;
ListNode* listB = headB;
int lenA = 0, lenB = 0;
while(listA != nullptr){
listA = listA->next;
lenA++;
}
while(listB != nullptr){
listB = listB->next;
lenB++;
}
if(lenB > lenA){
swap(headA, headB);
swap(lenA, lenB);
}
int gap = lenA - lenB;
listA = headA;
listB = headB;
while(gap--){
listA = listA->next;
}
while(listA != nullptr && listB != nullptr){
if(listA == listB){
return listA;
}else{
listA = listA->next;
listB = listB->next;
}
}
return nullptr;
}
142.环形链表II://需理解为甚么fast比slow快1就能在环中相遇,什么时候fast追上slow,以及追上后如何获取环的入口位置
ListNode *detectCycle(ListNode *head) {
ListNode* fast = head;
ListNode* slow = head;
while(fast != nullptr && fast->next != nullptr){
fast = fast->next->next;
slow = slow->next;
//找到fast与slow在环中的相遇点
if(fast == slow){
ListNode* left = head;
ListNode* right = fast;
while(left != nullptr && right != nullptr){
if(left == right){
return left;
}
left = left->next;
right = right->next;
}
}
}
return nullptr;
}