您的位置:首页 > 职场人生

剑指offer之面试题15-2:单链表是否有环

2016-04-23 15:35 681 查看
题目描述

判断一个单链表是否形成了环形结构。

思路:首先,有环的定义是,链表的尾节点指向了链接中间的某个节点。比如下图,如果单链表有环,则在遍历时,在通过6之后,会重新回到3,这道题和求链表的倒数第k个结点一样,采用的思想都是定义两个指针,使两指针在遍历时以某种方式错开,最后看两个指针是否相等。错开方式有两种。



solution1:使用pHead、pBehind两个指针,pHead一直向前走,pBehind每次都从头开始走,对于每个结点,看pHead走的步数是否和pBehind一致。如pHead从6走到3,走了6步,而pBehind走了2步骤,步数不一致,说明有环。

代码如下:

/**
* Definition for singly-linked list.
* class ListNode {
*     int val;
*     ListNode next;
*     ListNode(int x) {
*         val = x;
*         next = null;
*     }
* }
*/
import java.util.*;
public class Solution {
/*public static class ListNode{
int val;
ListNode next;
ListNode(int x){
val=x;
next=null;
}
}*/
public static boolean hasCycle(ListNode head) {
if(head==null)
return false;
ListNode pHead=head;
ListNode pBehind=null;
int pos1=0;
while(pHead.next!=null){
pos1++;
pBehind=head;
int pos2=0;
while(pBehind.next!=null){
pos2++;
if(pHead==pBehind){
if(pos1!=pos2){
return true;
}
else
break;
}
pBehind=pBehind.next;
}//end while
pHead=pHead.next;
}//end while
return false;
}
/*public static void main(String[] args){
List<ListNode> list=new ArrayList<ListNode>();
list.add(new ListNode(1));
list.add(new ListNode(2));
list.add(new ListNode(3));
list.add(new ListNode(4));
list.add(new ListNode(5));
list.add(new ListNode(6));
for(int i=0;i<list.size();i++){
ListNode listNode=list.get(i);
if(i+1<list.size()){
listNode.next=list.get(i+1);
}
//add a loop 6-->3
listNode.next=list.get(2);
}
if(hasCycle(list.get(0))){
System.out.println("List has loop");
}
}*/
}


solution2:使用pFast、pSlow两个指针,pFast每次向前走2步,pSlow每次向前走1步,若在某个时候pFast== pSlow,则存在环。

牛客网提交成功:

public static boolean hasCycle(ListNode head) {
if(head==null)
return false;
ListNode pFast=head;//一次走两步
ListNode pSlow=head;//一次走一步
while(pFast.next!=null&&pSlow.next!=null&&pFast.next.next!=null){
pFast=pFast.next.next;
pSlow=pSlow.next;
if(pFast==pSlow){
return true;
}

}//end while
return false;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: