两两交换
对交换的操作弄懂了,但一些起始条件的信息还是不懂
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
ListNode* dummyHead = new ListNode(0);
dummyHead->next = head;
ListNode* cur = dummyHead;
while(cur->next != nullptr && cur->next->next != nullptr) {
ListNode* temp = cur->next;
ListNode* temp1 = cur->next->next->next;
cur->next = cur->next->next;
cur->next->next = temp;
temp->next = temp1;
cur = cur->next->next;
}
return dummyHead->next;
}
};
19删除链表倒数节点
关键在于找到倒数第n个节点
对定义指针还不太熟悉
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode* dummyHead = new ListNode(0);
dummyHead->next = head;
ListNode* fast = dummyHead;
ListNode* slow = dummyHead;
n++;
while(n-- && fast != nullptr) {
fast = fast->next;
}
while(fast != nullptr) {
fast = fast->next;
slow = slow->next;
}
slow->next = slow->next->next;
return dummyHead->next;
}
};
环形链表
这就完全不会了
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 index1;
}
}
return NULL;
}
};
面试题链表相交先没思考
class Solution {
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
ListNode* curA = headA;
ListNode* curB = headB;
int lenA = 0, lenB = 0;
while(curA != NULL) {
lenA++;
curA = curA->next;
}
while(curB != NULL) {
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;
}
};