Как решить Искупление Иосифа, используя Круговой связанный список - PullRequest
1 голос
/ 12 ноября 2011
    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;
         }
    }

Я использую счетчик как 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);
    }
}

У меня проблема с методом исключения, я хочу, чтобы его постоянно вызывалипока список не пуст,

1 Ответ

1 голос
/ 12 ноября 2011

Я бы сделал:

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;
}
...