Пока петля с указателями не работает

0

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

// n,n1,head,next - are pointers
int j = 0; //this number helps to put pointer forward by one place
while(n!=0){//should go through every digit of the list
    if(head == 0){
        cout << "list is empty" << endl;
    }
    else{
        n = head;
        n1=0; // n1 and n are pointers
        while(n!=0){
            if(n->sk == maxx){//searches for maximum digit in the list
                break;
            }
            else{
                n1=n;
                n=n->next;
            }
        }
        if(head == n){
            head = head->next;
        }
        else{
            n1->next = n->next;
        }
        delete n; // deletes the pointer holding the highest value
    }
    n = head; //problem is here or somewhere below
    j++;
    for(int i=0; i<j;i++){ // this loop should make the pointer point to the first
        n = n->next;       // number, then the second and so on until the end of list
    }                      // and all the numbers inside the list with the value that
}                      // equals "maxx" should be deleted
Теги:
list
pointers

3 ответа

0
Лучший ответ

Хорошо, проблема (большая часть) - это код:

   while(n!=0){
        if(n->sk == maxx){
            break;
        }
        else{
            n1=n;
            n=n->next;
        }
    }

Если вы найдете значение maxx вы должны удалить этот узел и продолжить поиск, не break. Таким образом вам не нужно столько кода для этой задачи.

while (n != 0){
    if (n->sk == maxx){
        node *prev = n->prev; // The previous node.
        node *tmp = n;        // this assume you have a class node.
                              // temporaly holds the pointer to n.
        prev->next = n->next; // Connect the previous node with the following one.
        n = n->next;          // advance n to the next node in the list.
        delete tmp;           // delete the node.
    }
}
  • 0
    Ваш ответ останется прежним, если список будет двусторонним?
  • 0
    Под двусторонним вы подразумеваете круговой?
Показать ещё 3 комментария
2

Вы должны разыгрывать указатели. Прямо сейчас вы указываете на их адреса. Посмотрите, поможет ли это решить вашу проблему.

0

Если я правильно понимаю, что вы хотите, вы можете просто перебрать свой список и сохранить указатель на удаление:

it = head;
pos = nullptr;
while (it != nullptr) {
    if(it -> sk == maxx) {
        pos = it; // save ptr
        it = it -> next;
        delete pos; // delete saved ptr
        pos = nullptr;
    }
}

Ещё вопросы

Сообщество Overcoder
Наверх
Меню