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; } }
作者:Pickle
声明:对于转载分享我是没有意见的,出于对博客园社区和作者的尊重一定要保留原文地址哈。
致读者:坚持写博客不容易,写高质量博客更难,我也在不断的学习和进步,希望和所有同路人一道用技术来改变生活。觉得有点用就点个赞哈。








浙公网安备 33010602011771号