A
A
Alon Mix2022-01-30 05:04:10
C++ / C#
Alon Mix, 2022-01-30 05:04:10

Joseph's task c++ with cyclic linked list link problem in 2nd queue?

The problem arises in 2 queues. For example, there are 10 wars, an interval of 2, and after 9 there is a war 1 (which is wrong)
56V9T.png

#include <iostream>
using namespace std;
 
struct Node
{
    int m_item;
    Node *m_next;
    Node(int item, Node *next) { m_item = item, m_next = next; }
};
 
int main()
{
    cout << "Voin: "; 
    int NumberOfElements = 0;
    cin >> NumberOfElements; 
    cout << "M: "; //  интервал
    int interval;
    cin >> interval; // ввод интервала
    Node *first = new Node(1, 0);
    first->m_next = first;
    Node *tmp = first;
    cout << "Deleted elements:" << endl;
    for (int i = 2; i <= NumberOfElements; ++i)
    {
        tmp->m_next = new Node(i, first);
        tmp = tmp->m_next;
    }
    while (tmp != tmp->m_next)
    {
        for (int i = 1; i < interval; ++i)
        {
            tmp = tmp->m_next;
        }
        Node *deleteNode = tmp->m_next;
        tmp->m_next = tmp->m_next->m_next;
 
        cout << tmp->m_item << endl;
        delete deleteNode;
    }
    cout << "Last warrior:" << tmp->m_item << endl;
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
W
Wataru, 2022-01-30
@wataru

It is necessary to display the removed element, right? You output the previous one. Well, since the first one is always deleted at the beginning, you must manually delete it before your cycle. It might be easier if you make a doubly linked list and write a function that removes an element and returns the next one. It would be better to use a do while loop in the solution - remove the element and move. Then check how many elements are left... Well, or you can use for - you know how many deletions there will be from n wars.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question