题解 | #判断链表中是否有环#
判断链表中是否有环
http://www.nowcoder.com/practice/650474f313294468a4ded3ce0f7898b9
给遍历过的节点加一个标记,当遍历到有标记的节点说明遇到了环,否则就不存在环。
/*
* function ListNode(x){
* this.val = x;
* this.next = null;
* }
*/
/**
*
* @param head ListNode类
* @return bool布尔型
*/
function hasCycle( head ) {
// write code here
while (head) {
if (head.flag ==undefined) {
head.flag = 1;
head = head.next;
} else if (head.flag == 1) {
return true;
}
}
return false;
}
module.exports = {
hasCycle : hasCycle
};