19.删除链表的倒数第 N 个结点、160.相交链表、142.环形链表 II
19.删除链表的倒数第 N 个结点-Medium
快慢指针实现
状态:已完成
// 19.删除链表的倒数第 N 个结点
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode* dummyHead = new ListNode(0);
dummyHead->next;
ListNode* fast = dummyHead;
ListNode* slow = dummyHead;
while(n-- && fast->next != NULL){
fast = fast->next;
}
fast = fast->next;
while(fast != NULL){
slow = slow->next;
fast = fast->next;
}
slow->next = slow->next->next;
return dummyHead->next;
}
};
160.相交链表-Easy
状态:已完成
代码随想录题解:
// 160.相交链表
class Solution {
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
ListNode* curA = headA;
ListNode* curB = headB;
int lenA = 0, lenB = 0; // A、B 链表长度
// 计算 A 链表长度
while(curA != NULL){
curA = curA->next;
lenA++;
}
// 计算 B 链表长度
while(curB != NULL){
curB = curB->next;
lenB++;
}
// curA 和 curB 回到各自链表起点
curA = headA;
curB = headB;
// 比较链表长度,让A链表最长
if(lenB > lenA){
swap(lenA, lenB);
swap(curA, curB);
}
// 计算链表长度差
int gap = lenA - lenB;
// 对齐末尾位置,保证 A、B 链表最后一位对齐
while(gap--){
curA = curA->next;
}
while(curA != NULL){
if(curA == curB){ // 找到相交结点
return curA; // 返回相交结点位置
}
curA = curA->next; // A链表按位往后走
curB = curB->next; // B链表按位往后走
}
return NULL; // 不相交返回NULL
}
};
142.环形链表 II-Medium
状态:已完成
代码随想录题解:
// 142.环形链表 II
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
ListNode* fast = head;
ListNode* slow = head;
while(fast != NULL && fast->next != NULL){
slow = slow->next;
fast = fast->next->next;
if(fast == slow){
ListNode* index1 = fast;
ListNode* index2 = head;
while(index1 != index2){
index1 = index1->next;
index2 = index2->next;
}
return index2;
}
}
return NULL;
}
};