zoukankan      html  css  js  c++  java
  • 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?

    本来不是很难的一题,提交了n遍,一直运行时错误,为什么呢?因为一个指针判断的问题,由于要向后移动两个指针,因为p->next也需要判断,而不能仅仅判断p,不然p=p->next->next会有问题。

    C++代码实现:

    #include<iostream>
    #include<new>
    using namespace std;
    
    #include<iostream>
    #include<new>
    using namespace std;
    
    //Definition for singly-linked list.
    struct ListNode
    {
        int val;
        ListNode *next;
        ListNode(int x) : val(x), next(NULL) {}
    };
    class Solution
    {
    public:
        ListNode *detectCycle(ListNode *head)
        {
            //创建一个环至少需要2个结点
            if(head==NULL||head->next==NULL)
                return NULL;
            ListNode *p=head;
            ListNode *pre=head;
            while(p&&p->next)
            {
                p=p->next->next;
                pre=pre->next;
                if(pre==p)
                    break;
            }
            if(p==NULL||p->next==NULL)
            {
                return NULL;
            }
            p=head;
            while(pre!=p)
            {
                //判断要放在前面,因为从头结点开始就是一个环时,两个指针会相遇在头结点,此时并不需要指针后移
                //if(pre==p)
                 //   return pre;
                pre=pre->next;
                p=p->next;
            }
            return p;
        }
        void createList(ListNode *&head)
        {
            ListNode *p=NULL;
            ListNode *cycle=NULL;
            int i=0;
            int arr[10]= {10,9,8,7,6,5,4,3,2,1};
            for(i=0; i<10; i++)
            {
                if(head==NULL)
                {
                    head=new ListNode(arr[i]);
                    if(head==NULL)
                        return;
                    //为了创建一个环,记录尾指针
                    cycle=head;
                }
                else
                {
                    p=new ListNode(arr[i]);
                    p->next=head;
                    head=p;
                }
            }
            cycle->next=head->next->next->next;
        }
    };
    
    int main()
    {
        Solution s;
        ListNode *L=NULL;
        s.createList(L);
        ListNode *head=L;
        L=s.detectCycle(L);
        head=L;
        while(L)
        {
            cout<<L->val<<" ";
            L=L->next;
            if(L==head)
                break;
        }
    }

    运行结果:

  • 相关阅读:
    火狐浏览器清理缓存快捷键
    SVN使用教程总结
    如何登陆服务器
    get、put、post、delete含义与区别
    zookeeper 半数可用/选举机制
    zookeeper 分布式安装/配置/启动
    lucene 统计单词次数(词频tf)并进行排序
    selenium 爬取空间说说
    MapReduce自定义InputFormat,RecordReader
    reduce 阶段遍历对象添加到ArrayList中的问题
  • 原文地址:https://www.cnblogs.com/wuchanming/p/4101510.html
Copyright © 2011-2022 走看看