• 15. Linked List Cycle && Linked List Cycle II


    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?

     说明:两个指针不同步长。

    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     ListNode *next;
     *     ListNode(int x) : val(x), next(NULL) {}
     * };
     */
    class Solution {
    public:
        bool hasCycle(ListNode *head) {
            ListNode *p1, *p2;
            p1 = p2 = head;
            while(p2 && p2->next && p2->next->next) {
                p2 = p2->next->next;
                p1 = p1->next;
                if(p1 == p2) return true;
            }
            return false;
        }
    };
    

    Linked List Cycle II

    Given a linked list, return the node where the cycle begins. If there is no cycle, return null.

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

     说明:在上题基础上,将一个指针放到链表头,步长都设为1,相遇节点。(可以计算)

    class Solution {
    public:
        ListNode *detectCycle(ListNode *head) {
            ListNode *p1, *p2;
            p1 = p2 = head;
            while(p2 && p2->next && p2->next->next) {
                p2 = p2->next->next;
                p1 = p1->next;
                if(p1 == p2) {
                    p1 = head;
                    while(p1 != p2) {
                        p1 = p1->next;
                        p2 = p2->next;
                    }
                    return p1;
                }
            }
            return NULL;
        }
    };
    

     ps: 推导

    链表长度为 a (非环)+ b (环)

    1. 快指针每次追上慢指针一步,肯定会相遇。

    2. 相遇时:

    fast - slow = nb  (n 为正整数) , 由条件 fast = 2slow , 得 slow = nb (n 为正整数) 。说明此时慢指针走了 nb 步。

    3. a+nb 步的位置为入口点。由上一步结论——相遇时慢指针走了 nb 步得知,慢指针再走 a 步即可到入口点。

    4. 链表头部放一指针,走 a 步到入口点。由 3 结论可知,和慢指针同时走,会同时到达入口点(都走 a 步)。

  • 相关阅读:
    pat 1027. Colors in Mars (20)
    pat 1035. Password (20)
    pat 1006. Sign In and Sign Out (25)
    pat 1031. Hello World for U (20)
    pat 1005. Spell It Right (20)
    pat 1002. A+B for Polynomials (25)
    pat 1008. Elevator (20)
    pat 1001. A+B Format (20)
    算法分析与设计实验四 密码算法
    Android通讯录管理(获取联系人、通话记录、短信消息)
  • 原文地址:https://www.cnblogs.com/liyangguang1988/p/3902289.html
Copyright © 2020-2023  润新知