代码随想录算法训练营Day4|24.两两交换链表中的节点 19.删除链表的倒数第N个节点 02.07.链表相交 142.环形链表II
24. 两两交换链表中的节点
struct ListNode* swapPairs(struct ListNode* head) {
struct ListNode* preHead = (struct ListNode*)malloc(sizeof(struct ListNode));
preHead->next = head;
struct ListNode* p = preHead;
while ((p->next != NULL) && (p->next->next != NULL)) {
struct ListNode* former = p->next;
struct ListNode* later = p->next->next;
former->next = later->next;
later->next = former;
p->next = later;
p = p->next->next;
}
return preHead->next;
}

19.删除链表的倒数第N个节点
struct ListNode* removeNthFromEnd(struct ListNode* head, int n) {
struct ListNode* preHead = (struct ListNode*)malloc(sizeof(struct ListNode));
preHead->next = head;
struct ListNode* fast = preHead;
struct ListNode* slow = preHead;
for (int i = 0; i <= n; i++) {
if(fast){
fast = fast->next;
}
}
while (fast) {
fast = fast->next;
slow = slow->next;
}
slow->next = slow->next->next;
return preHead->next;
}

面试题 02.07. 链表相交
long getListNodeLength(struct ListNode *head){
long count = 0;
struct ListNode* p = head;
while (p) {
count++;
p = p->next;
}
return count;
}
struct ListNode *getIntersectionNode(struct ListNode *headA, struct ListNode *headB) {
long lengthA = getListNodeLength(headA);
long lengthB = getListNodeLength(headB);
struct ListNode* preHeadA = (struct ListNode*)malloc(sizeof(struct ListNode));
preHeadA->next = headA;
struct ListNode* pA = preHeadA;
struct ListNode* preHeadB = (struct ListNode*)malloc(sizeof(struct ListNode));
preHeadB->next = headB;
struct ListNode* pB = preHeadB;
if(lengthA > lengthB){
long offset = lengthA - lengthB;
for (int i = 0; i < offset; i++) {
pA = pA->next;
}
}else{
long offset = lengthB - lengthA;
for (int i = 0; i < offset; i++) {
pB = pB->next;
}
}
while (pA != NULL && pB != NULL) {
if(pA == pB){
return pA;
}
pA = pA->next;
pB = pB->next;
}
return NULL;
}

142.环形链表II
struct ListNode *detectCycle(struct ListNode *head) {
struct ListNode* fast = head;
struct ListNode* slow = head;
while (fast != NULL && fast->next != NULL) {
slow = slow->next;
fast = fast->next->next;
if (slow == fast) {
struct ListNode* index1 = fast;
struct ListNode* index2 = head;
while (index1 != index2) {
index1 = index1->next;
index2 = index2->next;
}
return index2;
}
}
return NULL;
}
