(整理)Java实现链表-----判断链表是否有环
2016-03-23 14:30
519 查看
import java.util.*; class Node{ Node next = null; int data; public Node(int data){ this.data = data; } } public class MyLinkedList { Node head = null; public void addNode(int d){ Node newNode = new Node(d); if(head == null){ head = newNode; return; } Node tmp = head; while(tmp.next != null){ tmp = tmp.next; } tmp.next = newNode; } public Boolean deleteNode(int index){ if(index<1||index>length()){ return false; } if(index == 1){ head = head.next; return true; } int i = 2; Node preNode = head; Node curNode = preNode.next; while(curNode != null){ if(i == index){ preNode.next = curNode.next; return true; } preNode = curNode; curNode = curNode.next; i++; } return true; } public int length(){ int length = 0; Node tmp = head; while(tmp != null){ length++; tmp = tmp.next; } return length; } public void printList(){ Node tmp = head; int i=0; while(tmp != null&&i<20){ i++; System.out.println(tmp.data); tmp = tmp.next; } } public Node findNode(int index){ int i; Node p = this.head; for(i = 1; i<index; i++){ p = p.next; } return p; } public boolean IsLoop(){//关键函数 Node fast = head;//快指针 Node slow = head;//慢指针 if(fast == null){ return false; } while(fast.next != null){//快指针是慢指针的二倍 fast = fast.next.next; slow = slow.next; if(fast == slow){//快慢相遇则有环,且此处为环的入口 return true; } } return false; } public void ReverseIteratively(){ Node head = this.head; Node pReversedHead = head; Node pNode = head; Node pPre = null; while(pNode != null){ Node pNext = pNode.next; if(pNext == null){ pReversedHead = pNode; } pNode.next = pPre; pPre = pNode; pNode = pNext; } this.head = pReversedHead; } public static void main(String[] args){ MyLinkedList list = new MyLinkedList(); list.addNode(7); list.addNode(6); list.addNode(5); list.addNode(4); list.addNode(3); list.addNode(2); list.addNode(1); Node p = list.findNode(4); Node p1 = list.findNode(7); // p1.next = p; list.printList(); boolean isloop = list.IsLoop(); System.out.println("isloop="+isloop); } }
测试结果:
7
6
5
4
3
2
1
isloop=false
去掉// 后测试结果:(有环会无限输出,这里仅输出前20个)
7
6
5
4
3
2
1
4
3
2
1
4
3
2
1
4
3
2
1
4
isloop=true
相关文章推荐
- java对世界各个时区(TimeZone)的通用转换处理方法(转载)
- java-注解annotation
- java-模拟tomcat服务器
- java-用HttpURLConnection发送Http请求.
- java-WEB中的监听器Lisener
- Android IPC进程间通讯机制
- Android Native 绘图方法
- Android java 与 javascript互访(相互调用)的方法例子
- 介绍一款信息管理系统的开源框架---jeecg
- 聚类算法之kmeans算法java版本
- java实现 PageRank算法
- PropertyChangeListener简单理解
- [C/C++]反转链表
- c++11 + SDL2 + ffmpeg +OpenAL + java = Android播放器
- 插入排序
- 冒泡排序
- 堆排序
- 快速排序