代码随想录Day4(24. 两两交换链表中的节点 ,19.删除链表的倒数第N个节点,160. 链表相交 ,142.环形链表II)
24. 两两交换链表中的节点
思路:
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
ListNode* dummyHead = new ListNode();
dummyHead->next = head;
if(head==nullptr||head->next==nullptr){
return head;
}
ListNode* result = head->next;
ListNode* cur = head;
ListNode* temp = cur->next;
while(temp!=nullptr){
dummyHead->next = temp;
ListNode* temp1 = temp->next;
temp->next = cur;
cur->next = temp1;
dummyHead = cur;
cur = cur->next;
if(cur==nullptr){
break;
}
temp = cur->next;
}
return result;
}
};
19.删除链表的倒数第N个节点
思路:fast,slow指针相差N,fast指针先到末尾,slow指针指到倒数第N个
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
if(head->next==nullptr){
return nullptr;
}
ListNode* dummyHead = new ListNode();
dummyHead->next = head;
ListNode* first = new ListNode();
first = dummyHead;
ListNode* second = new ListNode();
second = first->next;
for(int i=0; i<n; i++){
second = second->next;
}
while(second!=nullptr){
first = first->next;
second = second->next;
}
first->next = first->next->next;
return dummyHead->next;
}
};
160. 链表相交
思路:链表相交要判断指针相同而不是值相同。
class Solution {
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
int lenA=0, lenB=0;
ListNode* curA = headA;
ListNode* curB = headB;
while(curA!=NULL){
curA = curA->next;
lenA++;
}
while(curB!=NULL){
curB = curB->next;
lenB++;
}
curA = headA;
curB = headB;
int gap;
if(lenA>lenB){
gap = lenA-lenB;
while(gap!=0){
curA = curA->next;
gap--;
}
}
else{
gap = lenB-lenA;
while(gap!=0){
curB = curB->next;
gap--;
}
}
while(curA!=NULL){
if(curA == curB){
return curA;
}
else{
curA = curA->next;
curB = curB->next;
}
}
return curA;
}
};
142.环形链表II
思路:
判断有环:fast指针每次走两步,slow指针每次走一步,fast和slow会相遇(即fast在环内以相对slow速度为1追击到);
找到入环节点:index1从相遇处出发,index2从头节点head出发,相遇的节点。
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 = fast;
ListNode* index2 = head;
while(index1!=index2){
index1 = index1->next;
index2 = index2->next;
}
return index1;
}
}
return NULL;
}
};
总结
双指针的应用