24. 两两交换链表中的节点
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
ListNode *dummy=new ListNode();
dummy->next=head;
ListNode *cur=dummy;
while(cur->next!=nullptr&&cur->next->next!=nullptr)
{
ListNode *temp=cur->next;
cur->next=temp->next;
temp->next=cur->next->next;
cur->next->next=temp;
cur=temp;
}
return dummy->next;
}
};
注意点:在草稿纸上画清楚过程,实在不行就多用几个指针
19. 删除链表的倒数第 N 个结点
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode *dummy=new ListNode();
dummy->next=head;
ListNode *slow=dummy;
ListNode *fast=dummy;
while(n--)
{
fast=fast->next;
}
while(fast->next!=nullptr)
{
fast=fast->next;
slow=slow->next;
}
ListNode *temp=slow->next;
slow->next=temp->next;
delete temp;
return dummy->next;
}
};
注意点:
本题的精髓就是:fast比slow先走n步,当fast->next=null时,slow正好在倒数第n个的前一个;
面试题 02.07. 链表相交
class Solution {
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
int lenA=0,lenB=0;
ListNode *curA=headA;
ListNode *curB=headB;
while(curA!=NULL)
{
lenA++;
curA=curA->next;
}
while(curB!=NULL)
{
lenB++;
curB=curB->next;
}
curA=headA;
curB=headB;
if(lenB>lenA)
{
swap(curB,curA);
swap(lenA,lenB);
}
int gap=lenA-lenB;
while(gap--)
{
curA=curA->next;
}
while(curA!=NULL&&curB!=NULL)
{
if(curA==curB)
return curA;
else
{
curA=curA->next;
curB=curB->next;
}
}
return NULL;
}
};
注意点:本题的精髓在于相交的链表末尾对齐,我们求出两个链表的长度,并求出两个链表长度的差值,然后让curA移动到,和curB 末尾对齐的位置
142. 环形链表 II
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
ListNode *slow=head;
ListNode *fast=head;
while(fast!=NULL&&fast->next!=NULL)
{
slow=slow->next;
fast=fast->next->next;
if(slow==fast)
{
ListNode *index1=head;
ListNode *index2=fast;
while(index1!=index2)
{
index1=index1->next;
index2=index2->next;
}
return index1;
}
}
return NULL;
}
};
打卡第四天
一共做了4题,需要重新做的题目有
面试题 02.07. 链表相交
142. 环形链表 II