代码随想录day4

24. 两两交换链表中的节点 

class Solution {
public:
    ListNode* swapPairs(ListNode* head) {
        ListNode* dummyhead=new ListNode(0);
        dummyhead->next=head;
        ListNode* cur=dummyhead;
        while(cur->next!=NULL&&cur->next->next!=NULL){
            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;
    }
};

错因:while循环最后忘记移动cur指针了,超时。

19.删除链表的倒数第N个节点 

快慢指针,快指针先移动n+1步,然后快慢指针同时移动知道快指针指向NULL,最后进行删除。

class Solution {
public:
    ListNode* removeNthFromEnd(ListNode* head, int n) {
        ListNode* dummyhead=new ListNode(0);
        dummyhead->next=head;
        ListNode* slow=dummyhead;
        ListNode* fast=dummyhead;
        n++;
        while(n--){
            fast=fast->next;
        }
        while(fast!=NULL){
            slow=slow->next;
            fast=fast->next;
        }
        slow->next=slow->next->next;
        return dummyhead->next;//head有可能已经被删除了
    }
};

面试题 02.07. 链表相交 

class Solution {
public:
    ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
        ListNode *ta=headA;
        ListNode *tb=headB;
        while(ta!=tb){
            //注意跳转和正常的移动应该是if,else关系,不然就会多走一步
            if(ta==NULL){
                ta=headB;
            }else{
                ta=ta->next;
            }
            
            if(tb==NULL){
                tb=headA;
            }else{
                tb=tb->next;
            }
        }
        return ta;
    }
};

这题需要注意指针正常的移动和跳转应该是if和else关系,不然会多走一步。

142.环形链表II 

快慢指针,满指针每次移动一步,快指针每次移动两步,如果有环,则一定会相遇。

class Solution {
public:
    ListNode *detectCycle(ListNode *head) {
        ListNode *slow=head;
        ListNode *fast=head;
        while(fast!=NULL&&fast->next!=NULL){
            fast=fast->next->next;
            slow=slow->next;
            if(fast==slow){
                ListNode *index1=head;
                ListNode *index2=fast;
                while(index1!=index2){
                    index1=index1->next;
                    index2=index2->next;
                }
                return index1;
            }
        }
        return NULL;
    }
};

你可能感兴趣的:(链表,数据结构)