剑指Offer-56
来源:互联网 发布:网络流行组合字 编辑:程序博客网 时间:2024/05/12 09:10
题目:
一个链表中包含环,如何找出环的入口结点?
实现
public class Solution56 { public static Node findEntryNode(Node head){ if(head==null){ return null; } Node slow = head; Node quick = head; boolean flag = false; while (quick != null && quick.next != null){ slow = slow.next; quick = quick.next.next; if(slow == quick){ flag = true; System.out.println("有环"); break; } } if(!flag){ System.out.println("无环"); return null; } slow = head; while (slow!=quick){ slow=slow.next; quick=quick.next; } return slow; } public static void main(String[] args) { test01(); test02(); test03(); } // 1->2->3->4->5->6 private static void test01() { Node n1 = new Node(1); Node n2 = new Node(2); Node n3 = new Node(3); Node n4 = new Node(4); Node n5 = new Node(5); Node n6 = new Node(6); n1.next = n2; n2.next = n3; n3.next = n4; n4.next = n5; n5.next = n6; Node result = findEntryNode(n1); if (result != null) { System.out.println(result.value); } } // 1->2->3->4->5->6 // ^ | // | | // +--------+ private static void test02() { Node n1 = new Node(1); Node n2 = new Node(2); Node n3 = new Node(3); Node n4 = new Node(4); Node n5 = new Node(5); Node n6 = new Node(6); n1.next = n2; n2.next = n3; n3.next = n4; n4.next = n5; n5.next = n6; n6.next = n3; Node result = findEntryNode(n1); if (result != null) { System.out.println(result.value); } } // 1->2->3->4->5->6 <-+ // | | // +---+ private static void test03() { Node n1 = new Node(1); Node n2 = new Node(2); Node n3 = new Node(3); Node n4 = new Node(4); Node n5 = new Node(5); Node n6 = new Node(6); n1.next = n2; n2.next = n3; n3.next = n4; n4.next = n5; n5.next = n6; n6.next = n6; Node result = findEntryNode(n1); if (result != null) { System.out.println(result.value); } }}
证明
阅读全文
0 0
- 【56-60】剑指offer
- 剑指Offer-56
- 剑指OFFER
- 剑指offer
- 剑指Offer
- 剑指offer
- 剑指Offer
- 剑指offer
- 剑指offer
- 剑指offer
- 剑指Offer
- 剑指offer
- 剑指offer
- 剑指Offer
- 剑指offer
- 剑指offer
- 《剑指offer》
- 剑指Offer
- 一款比较好的java和scala开发工具,界面和eclipse一样
- 七 mysql连接池
- 【IntelliJ IDEA java-web 初学之容易遇到的问题及解决办法】
- 线性回归
- 数据库执行sql的大致流程——如何优化
- 剑指Offer-56
- SDUTOJ 3443 找老乡
- 微信小程序周报(第十三期)-极乐商店(store.dreawer.com)出品
- ios常见错误—— -[_NSString absoluteURL](请求网络图片)
- Spring各个版本新特性
- ORA-16714: the value of property ArchiveLagTarget is inconsistent with the database setting
- java.lang.IllegalStateException: Failed to load ApplicationContext
- 八、发送邮件
- 十条不错的编程观点