牛客地址
解题思路
import java.util.*;
public class Solution {
/**
*
* @param n int整型
* @param m int整型
* @return int整型
*/
class Ring{
class RingNode{
int val;
RingNode next;
public RingNode(int val){
this.val = val;
}
}
RingNode head = null;
RingNode tail = null;
public void add(int val){
if(head == null){
head = new RingNode(val);
head.next = head;
tail = head;
}
else{
tail.next = new RingNode(val);
tail = tail.next;
tail.next = head;
}
}
public int delete(int m){
if(m == 1){
return tail.val;
}
//只剩下一个节点
if(head.next == head){
return head.val;
}
RingNode curPre = null;
RingNode cur = head;
for(int i = 1; i < m; i++){
curPre = cur;
cur = cur.next;
}
//cur为待删除的节点
//如果删除的是头节点
if(cur == head){
tail.next = head.next;
head = tail.next;
}
//如果删除的是尾节点
else if(cur == tail){
tail = curPre;
tail.next = head;
}
else{
head = cur.next;
tail = curPre;
curPre.next = cur.next;
}
return -1;
}
}
public int ysf (int n, int m) {
// write code here
Ring ring = new Ring();
for(int i = 1; i <= n; i ++){
ring.add(i);
}
int res = -1;
while(true){
res = ring.delete(m);
if(res != -1){
break;
}
}
return res;
}
}