gpt4 book ai didi

c# - 如何使用循环链表解决 Josephus Elimination

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:10:59 26 4
gpt4 key购买 nike

    class Node
{
public int Data { get; set; }

public Node Next { get; set; }

public int Counter { get; set; }

public Node(int element,int counter)
{
Data = element;
Counter = counter;
Next=null;
}
}

我使用 counter 作为 person 的 TAG,或者换句话说,就是消除开始的位置。

class CircularLinkedList
{
Node first;
Node last;

public CircularLinkedList()
{
first = last = null;
}

protected void Insert(int element,int counter)
{
if (IsEmpty())
{
first = last = new Node(element,counter);
}
else
{
last.Next = last = new Node(element,counter);
last.Next = first;
}
}

public int RemoveAt(int index)
{
int value = 0;
Node current = first;
do
{
if (current.Counter == index)
{
value = current.Data;
}
current = current.Next;
} while (current != first);
return value;
}

public void AddMen(int n)
{
for (int i = 1; i <= n; i++)
{
Insert(i*2,i);
}
}

public int Eliminate(int m)
{
int value = 0;
Node current = first;
do
{
value = RemoveAt(m);

current = current.Next;

} while (current != first);
return value;
}

public bool IsEmpty()
{
return first == null;
}

public void Display()
{
Node current = first;
do
{
Console.WriteLine(current.Counter+" "+current.Data+" ");
current = current.Next;
} while (current!=first);
}
}

我对消除方法有问题,我希望它必须不断调用直到列表为空,

最佳答案

我会这样做:

public int Eliminate(int m)
{
int value = 0;
Node current = first;
Node nextNode;



do
{
nextNode = current.next;
value = RemoveAt(m);

current = nextNode;

} while (current != first);
return value;
}

关于c# - 如何使用循环链表解决 Josephus Elimination,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8104593/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com