zoukankan      html  css  js  c++  java
  • LeetCode141:Linked List Cycle

    题目:

    Given a linked list, determine if it has a cycle in it.

    Follow up:
    Can you solve it without using extra space?

    解题思路:

    判断链表有无环,可用快慢指针进行,快指针每次走两步,慢指针每次走一步,如果快指针追上了慢指针,则存在环,否则,快指针走到链表末尾即为NULL是也没追上,则无环。

    为什么快慢指针可以判断有无环?

    因为快指针先进入环,在慢指针进入之后,如果把慢指针看作在前面,快指针在后面每次循环都向慢指针靠近1,所以一定会相遇,而不会出现快指针直接跳过慢指针的情况。

    实现代码:

    #include <iostream>
    using namespace std;
    
    /**
    Linked List Cycle
     */
     
    struct ListNode {
         int val;
         ListNode *next;
         ListNode(int x) : val(x), next(NULL) {}
    };
    void addNode(ListNode* &head, int val)
    {
        ListNode *node = new ListNode(val);
        if(head == NULL)
        {
            head = node;
        }
        else
        {
            node->next = head;
            head = node;
        }
    }
    void printList(ListNode *head)
    {
        while(head)
        {
            cout<<head->val<<" ";
            head = head->next;
        }
    }
    
    class Solution {
    public:
        bool hasCycle(ListNode *head) {
            if(head == NULL || head->next == NULL)
                return NULL;
            ListNode *quick = head;
            ListNode *slow = head;
            while(quick && quick->next)//利用快慢指针判断有无环 
            {
                quick = quick->next->next;
                slow = slow->next;
                if(quick == slow)
                    return true;
            }
            return NULL;
                  
        }
    };
    int main(void)
    {
        ListNode *head = new ListNode(1);
        ListNode *node1 = new ListNode(2);
        ListNode *node2 = new ListNode(3);
        ListNode *node3 = new ListNode(4);
        head->next = node1;
        node1->next = node2;
        node2->next = node3;
        node3->next = node1;
        
        Solution solution;
        bool ret = solution.hasCycle(head);
        if(ret)
            cout<<"has cycle"<<endl;
        
        return 0;
    }
  • 相关阅读:
    1、springcloud gateway
    -webkit-overflow-scrolling:touch 相关
    SpringBoot(一)原理剖析:SpringApplication启动原理
    JAVA基础面试题
    JVM面试题
    排序(四)选择排序:简单选择排序
    排序(三)插入排序:简单插入排序和希尔排序
    排序(二)交换排序:冒泡排序与快速排序
    排序(一)简介
    多线程面试题
  • 原文地址:https://www.cnblogs.com/mickole/p/3671475.html
Copyright © 2011-2022 走看看