标签:strong getc asc 一点 否则 var ast 入口 blog
1.单链表是否有环
使用快慢指针,都从head出发,慢指针一次一步,快指针一次两步,如果两个指针相遇,说明链表有环,否则,快指针为null或其next为null,到达末尾节点
function hasCircle(head){ var slow = head, fast = head; while(fast && fast.next){ slow = slow.next; fast = fast.next.next; if(slow == fast){ break; } } return fast != null && fast.next != null; }
2.单链表环的入口点
使用快慢指针,先判断是否有环,若有环,则慢指针从head出发,快指针与其同样的速度运行,直到相遇的一点,即为环入口点。
function getCircleEntry(head){ var slow = head, fast = head; while(fast && fast.next){ slow = slow.next; fast = fast.next.next; if(slow == fast){ break; } } if(fast == null || fast.next == null){ return null; } slow = head; while(slow != fast){ slow = slow.next; fast = fast.next; } return fast; }
3. 单链表环的大小
指针绕环一圈,记录其走过的步数,即为环大小
function getCircleLen(head){ var entry = getCircleEntry(head), len = 0 if(entry){ var p = entry; while(p != entry){ len++; p = p.next; } } return len; }
4. 解开一个环
function breakCircle(head){ var entry = getCircleEntry(head); if(entry){ var p = entry; while(p.next != entry){ p = p.next; } p.next = null; } }
标签:strong getc asc 一点 否则 var ast 入口 blog
原文地址:http://www.cnblogs.com/mengff/p/6892079.html