zoukankan      html  css  js  c++  java
  • 链表中环

    思路:

    1.将ListNode一个个放入set,并检查是否已经存在set中

    2.双指针,快慢指针

    判断是否有环比较简单,找环的起点浮复杂一些。

    #include <iostream>
    #include <set>
    using namespace std;
    
    struct ListNode
    {
        int val;
        ListNode* next;
        ListNode(int x) : val(x), next(NULL) {}
    };
    
    ListNode* findloop(ListNode* head)
    {
        set<ListNode*> set;
        while(head)
        {
            if(set.find(head) != set.end())
                return head;
            set.insert(head);
            head = head->next;
        }
        return NULL;
    }
    
    ListNode* findloop1(ListNode* head)
    {
        ListNode* prehead = head;
        ListNode* fast = prehead;
        ListNode* slow = prehead;
        while(fast)
        {
            slow = slow->next;
            fast = fast->next;
            if(!fast)   //至少要走两个节点
                return NULL;
            fast = fast->next;
            if(slow == fast)
                break;
        }
        cout << fast->val<< endl;
        cout << slow->val<< endl;
        if(slow != fast)
            return NULL;
        while(1)    //一定有环了
        {
            if(slow == prehead)
                return prehead;
            prehead = prehead->next;
            slow = slow->next;
        }
        return NULL;
    }
    
    int main()
    {
        ListNode l1(7);
        ListNode l2(8);
        ListNode l3(9);
        ListNode a(0);
        ListNode b(1);
        ListNode c(2);
        ListNode d(3);
        ListNode f(4);
        ListNode e(5);
        ListNode g(6);
        l1.next = &l2;
        l2.next = &a;
        l2.next = &a;
        a.next = &b;
        b.next = &c;
        c.next = &d;
        d.next = &f;
        f.next = &e;
        e.next = &a;
        cout << findloop1(&l1)->val << endl;
        return 0;
    }
  • 相关阅读:
    线程
    简单排序
    SSM的整合
    SpringMVC中的拦截器、异常处理器
    SpringMVC的文件上传
    SpringMVC的数据响应和结果视图
    springMVC的常用注解
    SpringMVC入门
    Spring中声明式事务控制
    JdbcTemplate在spring中的使用
  • 原文地址:https://www.cnblogs.com/11ys/p/14277262.html
Copyright © 2011-2022 走看看