zoukankan      html  css  js  c++  java
  • LeetCode——Linked List Cycle

    Description:

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

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

    在不借助辅助空间的情况下判断一个链表是否存在回路。

    可以用两个指针,一个从头节点开始,一个从头节点的next节点开始,node1一次走一步,node2一次走两步,这样一来如果链表存在回路的话,这两个节点就会相遇。否则则不存在回路。

    /**
     * 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) {
            
            if(head == null) {
                return false;
            }
            
            ListNode node1 = head, node2 = head.next;
            
            while(node1 != null && node2 != null && node2.next != null) {
                if(node1 == node2) {
                    return true;
                }
                node1 = node1.next;
                node2 = node2.next.next;
            }
            
            return false;
            
        }
    }
  • 相关阅读:
    ajax的post请求
    ajax的get请求
    浏览器缓存机制
    php和cookie
    php表单(2)
    php和表单(1)
    枚举for/in
    .Matrix-Beta冲刺的汇总博客
    .Matrix汇总博客
    小黄衫获得的感想
  • 原文地址:https://www.cnblogs.com/wxisme/p/4844538.html
Copyright © 2011-2022 走看看