题目
给定一个链表,判断链表中是否有环。为了表示给定链表中的环,我们使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。 如果 pos 是 -1,则在该链表中没有环。
分析
快慢指针,快指针一次两步慢指针一次一步。当快指针走到空时证明无环。
如果有环,快慢指针必相遇。
相遇后快指针回到起点,和慢指针一起走,再次相遇时为入口。
公式推导
环外链表的长度 = 第一次相遇点 + n-1次环的长度
代码
public class ListNode{
int val;
ListNode next;
public ListNode(int data) {
this.val = data;
next = null;
}
}
public boolean hasCycle(ListNode head) {
if (head == null || head.next == null) {
return false;
}
// 起点不同是因为while的判断条件
ListNode slow = head;
ListNode fast = head.next;
while (slow != fast) {
if(fast.next==null || fast.next.next==null) return false;
slow = slow.next;
fast = fast.next.next;
}
return true;
}
public boolean hasCycle1(ListNode head) {
if(head==null || head.next==null) return false;
ListNode slow = head;
ListNode fast = head;
while(true){
if(fast.next==null || fast.next.next==null) return false;
slow = slow.next;
fast = fast.next.next;
if(slow==fast) break;
}
return true;
}
题目描述
描述
编号为 11 到 nn 的 nn 个人围成一圈。从编号为 11 的人开始报数,报到 mm 的人离开。
下一个人继续从 11 开始报数。
n-1n−1 轮结束以后,只剩下一个人,问最后留下的这个人编号是多少?
输入:
5,2
返回值:
3
说明:
开始5个人 1,2,3,4,5 ,从1开始报数,1->1,2->2编号为2的人离开
1,3,4,5,从3开始报数,3->1,4->2编号为4的人离开
1,3,5,从5开始报数,5->1,1->2编号为1的人离开
3,5,从3开始报数,3->1,5->2编号为5的人离开
最后留下人的编号是3
代码
import java.util.*;
public class Solution {
/**
*
* @param n int整型
* @param m int整型
* @return int整型
*/
public int ysf (int n, int m) {
// write code here
ListNode head=new ListNode(1);
ListNode tail=head;
for(int i=2;i<=n;i++){
tail.next=new ListNode(i);
tail=tail.next;
}
tail.next=head;
ListNode index=head;
ListNode pre=tail;
int k=0;
while(index.next!=null&&index.next!=index){
k++;
ListNode next=index.next;
if(k==m){
pre.next=pre.next.next;
k=0;
}
pre=index;
index=next;
}
return index.val;
}
}