参考大佬题解
环形链表
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public boolean hasCycle(ListNode head) {
ListNode slow=head;
ListNode fast=head;
while(true){
if(fast==null||fast.next==null){
return false;
}
slow=slow.next;
fast=fast.next.next;
if(slow==fast)
return true;
}
}
}
环形链表II
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode detectCycle(ListNode head) {
ListNode slow=head;
ListNode fast=head;
while(true){
if(fast==null||fast.next==null){
return null;
}
slow=slow.next;
fast=fast.next.next;
if(slow==fast)
break;
}
fast=head;
while(fast!=slow){
fast=fast.next;
slow=slow.next;
}
return fast;
}
}
题解思路:追及相遇问题
快乐数
class Solution {
public boolean isHappy(int n) {
int fast = n;
int slow = n;
while(true){
fast=getnext(fast);
fast=getnext(fast);
slow=getnext(slow);
if(fast==1) return true;
if(fast==slow) return false;
}
}
int getnext(int n){
int sum=0;
int help=0;
while(n>0){
help=n%10;
sum+=help*help;
n=n/10;
}
return sum;
}
解题思路: