Leetcode习题集-链表

这里记录一些我刷题的思路方便之后进行复习重温,同时也方便进行添加

P141-环形链表

class Solution {
public:
    bool hasCycle(ListNode *head) {
        if(!head) return false;
        if(!head->next) return false;
        ListNode* last = reverse(head);
        return last==head;
    }
    
    ListNode* reverse(ListNode* head){
        ListNode *pre=NULL,*curr=head;
        while(curr){
            ListNode* next = curr->next;
            curr->next=pre;
            pre=curr;
            curr=next;
        }
        return pre;
    }
};

使用翻转链表,判断返回的指针与传进的指针是否相同,时间复杂度是O(N)(?可能),空间复杂度是O(1).

class Solution {
public:
    bool hasCycle(ListNode *head) {
        if(!head||!head->next) return false;
        ListNode *fast=head->next,*slow=head;
        while(fast!=slow){
            if(!fast||!fast->next) return false;
            fast=fast->next->next;
            slow=slow->next; 
        }
        return true;
    }
};

使用快慢指针Floyd 判圈算法,如果有环则兔子会与龟碰上,但没有环则会到NULL,这里有一个小知识点就是!fast||!fast->next这个条件需要先判断fast是否为空,顺序不能翻转否则可能进入死循环,因为判断的顺序从左到右。

p19-删除链表的倒数第N个节点

class Solution {
public:
    ListNode* removeNthFromEnd(ListNode* head, int n) {
        head=reverse(head);
        int i=1;
        ListNode* ptr=head;
        if(i==n) return reverse(head->next);
        i++;
        while(ptr&&ptr->next){
            if(i==n){
                ptr->next=ptr->next->next;
                break;
            } 
            ptr=ptr->next;
            i++;
        }
        return reverse(head);
    }
    
    ListNode* reverse(ListNode* head){
        ListNode* pre=NULL,*curr=head;
        while(curr){
            ListNode* next = curr->next;
            curr->next=pre;
            pre=curr;
            curr=next;
        }
        return pre;
    }
};

两次翻转。

class Solution {
public:
    ListNode* removeNthFromEnd(ListNode* head, int n) {
        ListNode *slow=head, *fast=head;
        while(n){
            fast=fast->next;
            n--;
        }
        if(!fast) return head->next;
        while(fast->next){
            fast=fast->next;
            slow=slow->next;
        }
        slow->next=slow->next->next;
        return head;
    }
};

快慢指针,将最后一段的间隔设定好,即快指针先跑结尾长度,然后双指针齐头并进。

posted @ 2021-01-16 16:11  xkyl  阅读(78)  评论(0编辑  收藏  举报