public StaticListNode(E data, int cursor) { this.data = data; this.cursor = cursor; }
public E getData() { return data; }
public void setData(E data) { this.data = data; }
public int getCursor() { return cursor; }
public void setCursor(int cursor) { this.cursor = cursor; } }
static class StcList<E> {
private static final int MAX_SIZE = 10; StaticListNode<E>[] nodes = new StaticListNode[MAX_SIZE];
public StcList() { initList(nodes, nodes.length); }
//初始化备用链表 private void initList(StaticListNode[] nodes, int maxSize) { for (int i = 0; i < maxSize; i++) { nodes[i] = new StaticListNode(null, i + 1); } //将最后一个数据元素的游标指向第一个有值元素 nodes[maxSize - 1] = new StaticListNode(null, 0); }
public void printAll() { for (int i = 0; i < nodes.length; i++) { System.out.print(nodes[i].getCursor()); System.out.print(":"); System.out.print(nodes[i].getData()); System.out.print(":"); System.out.print(i); System.out.print("|"); } System.out.println(); }
/** * 查找当前备用链表的头的 */ private void findHead() {
}
/** * 分配空间 分配空间的元素下标 * * @return 0分配失败 */ private int mallocArry() { int index = 0; if (nodes[0].cursor > 0) { index = nodes[0].cursor; nodes[0].cursor = nodes[index].cursor; } return index; }
//顺序新增元素 public boolean add(E e) { if (e == null) { System.out.println("新增失败"); return false; }
//不等于零说明链表容量没用完,可以新增 int currentIndex = nodes[0].getCursor(); if (currentIndex > 0) { //当前空元素下标 nodes[currentIndex].setData(e); nodes[0].setCursor(nodes[currentIndex].getCursor()); // nodes[currentIndex].setCursor(0);
return true; }
System.out.println("新增失败"); return false; }
/** * @param e 要插入的数据 * @param index 表示要插入的链中的位置 * @return true插入成功 */ //新增元素 public boolean insert(E e, int index) { if (e == null || index < 0 || index > MAX_SIZE - 1) { System.out.println("插入元素失败"); return false; }
//不等于零说明链表容量没用完,可以新增 int currentIndex = nodes[0].getCursor(); if (currentIndex > 0) {
//查找对应的位置 int k = 1; for (int i = 0; i < index - 1; i++) { k = nodes[k].cursor; }
//要插入位置记录的游标 int insertCursor = nodes[k].getCursor();
//不等于零说明链表容量没用完,可以新增 int currentEmptyIndex = nodes[0].getCursor(); if (currentEmptyIndex > 0) { //查找前一个的位置 int k = 1; for (int i = 1; i < index - 1; i++) { k = nodes[k].cursor; }
int currentIndex = nodes[k].cursor; int nextIndex = nodes[currentIndex].cursor; nodes[k].cursor = nextIndex;
#include <stdio.h> int main() { int n, m, i, winner = 0; printf ("N M = "); scanf("%d%d", &n, &m); for (i = 2; i <= n; i++) { //i是每阶约瑟夫环的人数 winner = (winner + m) % i; } //编号是从零开始,这里加1变成符合习惯的计数 printf ("\nThe winner is %d\n", (winner +1)); }