141.[LeetCode]Linked List Cycle

来源:互联网 发布:软件测试简历模板 编辑:程序博客网 时间:2024/05/16 06:36

题意:找一个单链中是否有环

我的解法

遍历单链,每次遍历 判断该节点的next 是否指向 head,如果指向说明是有环的,如果没指向则移动到下一个并把此节点的next指向head—缺点:会破坏此链,不过时间复杂度只要O(n)

class Solution {public:    bool hasCycle(ListNode *head) {        if(head == NULL) return false;        ListNode *temp = head->next,*next; // 连续申明两个指针        head->next = head;        while(temp != NULL){            next = temp->next;            if(next == head) return true;            temp->next = head;            temp = next;        }        return false;    }};

另一种方法

思路就是设定两个指针一起来遍历整个链,一个遍历的速度快,另一个的慢,如果有环的话,其中快的总会指向慢的,如果快的先指向null说明无环

class Solution {public:    bool hasCycle(ListNode *head) {        if(head == NULL || head->next == NULL) return false;        ListNode *slow = head,*fast = head->next;        while(slow != fast){            if(fast == NULL || fast->next == NULL) return false;            slow = slow->next;            fast = fast->next->next; // fast前进更快        }        //一旦相等,说明有环        return true;    }};

另另一 种方法

使用hashset

//这是java的public boolean hasCycle(ListNode head) {    Set<ListNode> nodesSeen = new HashSet<>();    while (head != null) {        if (nodesSeen.contains(head)) {            return true;        } else {            nodesSeen.add(head);        }        head = head.next;    }    return false;}
0 0
原创粉丝点击