206.反转链表
![在这里插入图片描述](https://img-blog.csdnimg.cn/afc4b9c012514f408c1f656960f7e560.png)
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode* cur = head;
ListNode* pre = nullptr;
ListNode* temp = nullptr;
while (cur != nullptr)
{
temp = cur->next;
cur->next = pre;
pre = cur;
cur = temp;
}
return pre;
}
};
![在这里插入图片描述](https://img-blog.csdnimg.cn/010fb15703954fe4acb07ecd6d1cd4ab.png)
24. 两两交换链表中的节点
![在这里插入图片描述](https://img-blog.csdnimg.cn/3481e06ee6fe4fa5b666c1b7398f6489.png)
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
ListNode* dummynode = new ListNode(0);
dummynode->next = head;
ListNode* cur = dummynode;
while (cur->next != nullptr && cur->next->next != nullptr)
{
ListNode* tmp1 = cur->next;
ListNode* tmp2 = cur->next->next->next;
cur->next = cur->next->next;
cur->next->next = tmp1;
cur->next->next->next = tmp2;
cur = cur->next->next;
}
return dummynode->next;
}
};
![在这里插入图片描述](https://img-blog.csdnimg.cn/f91fd63c650d4e609baa2b8a7f8f285f.png)
19. 删除链表的倒数第 N 个结点
![在这里插入图片描述](https://img-blog.csdnimg.cn/ddbd7336019b4482b22b154a5fbdabf8.png)
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode* dummynode = new ListNode(0);
dummynode->next = head;
ListNode* fast = dummynode;
ListNode* slow = dummynode;
while (n-- && fast != nullptr)
{
fast = fast->next;
}
fast = fast->next;
while (fast != nullptr)
{
slow = slow->next;
fast = fast->next;
}
slow->next = slow->next->next;
return dummynode->next;
}
};
![在这里插入图片描述](https://img-blog.csdnimg.cn/34018078e9e140de9ad9fe9f2d53b978.png)
面试题 02.07. 链表相交
![在这里插入图片描述](https://img-blog.csdnimg.cn/8b8cf7e005b8425e947092d6ece624e2.png)
class Solution {
public:
ListNode* getIntersectionNode(ListNode* headA, ListNode* headB) {
ListNode* curA = headA;
ListNode* curB = headB;
int lenA = 0;
int lenB = 0;
while (curA != nullptr)
{
lenA++;
curA = curA->next;
}
while (curB != nullptr)
{
lenB++;
curB = curB->next;
}
curA = headA;
curB = headB;
if (lenB > lenA)
{
swap(lenA, lenB);
swap(curA, curB);
}
int gap = lenA - lenB;
while (gap--)
{
curA = curA->next;
}
while (curA != nullptr)
{
if (curA == curB)
{
return curA;
}
curA = curA->next;
curB = curB->next;
}
return nullptr;
}
};
![在这里插入图片描述](https://img-blog.csdnimg.cn/a6ca81f5d40c44f58182e8740d53b489.png)
142.环形链表II
![在这里插入图片描述](https://img-blog.csdnimg.cn/de1e2a5e8948407b9f4be5f9003f6e03.png)
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 nullptr;
}
};
![在这里插入图片描述](https://img-blog.csdnimg.cn/6d1032a6ed3b46caa10ca8031d807582.png)