zoukankan      html  css  js  c++  java
  • 腾讯//环形链表

    环形链表

    给定一个链表,判断链表中是否有环。

    进阶:
    你能否不使用额外空间解决此题?

    (转化为追击相遇问题)

    /**
     * Definition for singly-linked list.
     * class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) {
     *         val = x;
     *         next = null;
     *     }
     * }
     */
    public class Solution {
        public boolean hasCycle(ListNode head) {
            ListNode slow = new ListNode(0);
            ListNode fast = new ListNode(0);
            if(head==null||head.next==null)
                return false;
            else{
                fast = head.next;
                slow = head;
                while(fast!=null){
                    if(fast.val == slow.val)
                        return true;
                    else{
                        fast = fast.next;
                        if(fast==null)
                            return false;
                        else{
                            fast = fast.next;
                            slow = slow.next;
                        }
                    }
                }
            }
            return false;
        }
    }
    /**
     * 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 *fast;
            ListNode *slow;
            if(head==nullptr||head->next==nullptr){
                return false;
            }else{
                fast = head->next;
                slow = head;
                while(fast!=nullptr){
                    if(fast==slow)
                        return true;
                    else{
                        fast = fast->next;
                        if(fast==nullptr)
                            return false;
                        else{
                            fast = fast->next;
                            slow = slow->next;
                        }
                    }
                }
                return false;
            }
        }
    };
  • 相关阅读:
    go语言关于线程与通道channal
    linux 搭建SVN服务端
    使用mbedtls的使用说明和AES加密方法(原来的PolarSSL)
    清理 Xcode 10 记录
    Windows下修改iTunes备份路径
    Winform窗口自适应
    修改类模板文件
    HashTable
    修改App.config的键和值
    博客园动画效果
  • 原文地址:https://www.cnblogs.com/strawqqhat/p/10602469.html
Copyright © 2011-2022 走看看