题解 | #判断链表中是否有环#
判断链表中是否有环
http://www.nowcoder.com/practice/650474f313294468a4ded3ce0f7898b9
逐个删除法:
思路:
遍历每个节点,将其自成环,并从链表中删除。
在遍历的过程中先判断该节点是否自成环,如已经自成环了,说明之前遍历过这个节点,并将其自成环过。
换句话说就是在遍历的过程中先判断 head==head.next,如果相等,说明说环形链表。
public boolean hasCycle(ListNode head) {
while(head != null){
if(head == head.next){
return true;
}
ListNode next = head.next;
head.next = head;
head = next;
}
return false;
}
SHEIN希音公司福利 280人发布

