亚马逊品牌备案网站怎么做,互联网上市公司一览表,南宁小程序开发网站建设公司,win2003 iis做网站目录 题目1- 思路2- 实现⭐141. 环形链表——题解思路 3- ACM实现 题目
原题连接#xff1a;141. 环形链表 1- 思路
模式识别
模式1#xff1a;判断链表的环 —— 快慢指针
思路
快指针 —— 走两步慢指针 —— 走一步判断环#xff1a;若快慢相遇则有环141. 环形链表 1- 思路
模式识别
模式1判断链表的环 —— 快慢指针
思路
快指针 —— 走两步慢指针 —— 走一步判断环若快慢相遇则有环若到终止条件 fast.next null || fast.next.next null 没有相遇返回false 2- 实现
⭐141. 环形链表——题解思路 public class Solution {public boolean hasCycle(ListNode head) {// 快慢指针ListNode slow head;ListNode fast head;while(fast!null fast.next!null){slow slow.next;fast fast.next.next;if(slowfast){return true;}}return false;}
}3- ACM实现
public class isCycle {static class ListNode{int val;ListNode next;ListNode(){}ListNode(int x){val x;}}public static boolean isCycle(ListNode head){// 快慢指针ListNode slow head;ListNode fast head;while(fast!null fast.next!null){slow slow.next;fast fast.next.next;if(slow fast){return true;}}return false;}public static void main(String[] args) {Scanner sc new Scanner(System.in);System.out.println(输入链表长度);int n sc.nextInt();ListNode head null,tail null;System.out.println(输入链表);for(int i 0 ; i n;i){ListNode newNode new ListNode(sc.nextInt());if(headnull){head newNode;tail newNode;}else{tail.next newNode;tail newNode;}}System.out.println(输入环的位置(第几个元素));int index sc.nextInt();ListNode cur head;for(int i 1 ; i index;i){cur cur.next;}tail.next cur;System.out.println(链表是否有环isCycle(head));}
}