Модераторы: Daevaorn
  

Поиск:

Ответ в темуСоздание новой темы Создание опроса
> Удаление элемента спсика 
:(
    Опции темы
lionwine
Дата 8.10.2014, 19:40 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Новичок



Профиль
Группа: Участник
Сообщений: 2
Регистрация: 8.10.2014

Репутация: нет
Всего: нет



Привет, всем. Очень нужна помощь в проблеме удаления элемента (или хотя бы исключения его из списка). Удаляет   строго 1 раз из любого места списка, затем при повторном программа вылетает.  Просто, уже столько времени убил на безрезультатные попытки что-либо поменять. Пробовал запускать на разных компиляторах. Смотрел иные коды. Хелп, плиз!!! Случай 4.
MainClass.cpp
Код
#include "MainClass.h"
#include <conio.h>
#include <iostream>
#include <windows.h>
#pragma warning (disable:4996)

MainClass* MainClass::current = NULL;    
MainClass* MainClass::head = NULL;
MainClass* MainClass::prev = NULL;
MainClass* MainClass::tail = NULL;
int MainClass::counter = 0;

MainClass::MainClass(){
    key = new char[20];
}
MainClass::~MainClass(){
    delete[] key;
}

int MainClass::getNumber(){
    return number;
}
void MainClass::setNumber(int number){
    this->number=number;
}
char* MainClass::getKey(){
    return key;
}
void MainClass::setKey(char* key){
    strcpy(this->key, key);
}
int MainClass::getIntKey(){
    return intKey;
}
void MainClass::setIntKey(int intKey){
    this->intKey = intKey;
}
MainClass* MainClass::getNext(){
    return next;
}
void MainClass::setNext(MainClass* next){
    this->next = next;
}

void MainClass::menu(){
        std::cout << "      MENU";
        std::cout << "\n\n1   - show list";
        std::cout << "\n2   - search by number";
        std::cout << "\n3   - add new element before max intKey";
        std::cout << "\n4   - delete element with max intKey";
        std::cout << "\nESC - Exit";
}
void MainClass::main(){
    //int n;
    //std::cout << "List's length? ";
    //std::cin >> n;
    createList(/*n*/);
    char keyMenu = '0';
    char* key = new char[20];
    int intKey = 0;
    int maxIntKey = INT_MIN;
    MainClass* temp = new MainClass;
    MainClass* temp2 = new MainClass;
    MainClass* lastEven = new MainClass;
    while (keyMenu != 27)
    {
        system("cls");
        menu();
        keyMenu = _getch();

        switch (keyMenu)
        {
        case '1':
            current = head;
            std::cout << "\n\nkey:\tintKey:\tnumber:";
            while (!current == NULL)
            {
                std::cout << "\n" << current->getKey() << "\t";
                std::cout << current->getIntKey() << "\t";
                std::cout << current->getNumber();
                current = current->getNext();
            }
            _getch();
            break;
        case '2':
            int searchNumber;
            std::cout << "\n\nnumber is?\t";
            std::cin >> searchNumber;
            std::cout << "\nkey:\tintKey:\tnumber:\n";

            current = head;
            while (!current == NULL)
            {
                if (current->getNumber() == searchNumber){
                    std::cout << current->getKey() << "\t";
                    std::cout << current->getIntKey() << "\t";
                    std::cout << current->getNumber();
                }
                current = current->getNext();
            }
            _getch();
            break;
        case '3':
            current = head;
            while (!current == NULL){
                if (maxIntKey < current->getIntKey())
                    maxIntKey = current->getIntKey();
                current = current->getNext();
            }
            //current = new MainClass;
            if (head->getIntKey() == maxIntKey){
                std::cout << "\nnew charKey is?\t";
                std::cin >> key;
                std::cout << "new intKey is?\t";
                std::cin >> intKey;
                current->setKey(key);
                current->setIntKey(intKey);
                current->setNumber(counter);
                counter++;
                current->setNext(head);
                head = current;
            }
            else{
                MainClass* additional = new MainClass;
                current = head;
                while (current)
                {
                    if (current->getNext()->getIntKey() == maxIntKey){
                        std::cout << "\nnew charKey is?\t";
                        std::cin >> key;
                        std::cout << "new intKey is?\t";
                        std::cin >> intKey;
                        additional->setKey(key);
                        additional->setIntKey(intKey);
                        additional->setNumber(counter);
                        counter++;
                        additional->setNext(current->getNext());
                        current->setNext(additional);
                        break;
                    }
                    current = current->getNext();
                }
            }
            _getch();
            break;
        case '4':
//_____________________________________________________________________________________________________________________________________
            /*
            current = head;
            while (!current == NULL){
            if (maxIntKey < current->getIntKey())
            maxIntKey = current->getIntKey();
            current = current->getNext();
            }
            if (head->getIntKey() == maxIntKey){
            current = head;
            head = NULL;
            //delete head;
            if (current->getNext()!=NULL)
            head = current->getNext();
            }
            else{
            current = head;
            while (current)
            {
            if (current->getNext()->getIntKey() == maxIntKey){
            //current->getNext() = NULL;
            current->setNext(current->getNext()->getNext());
            break;
            }
            current = current->getNext();
            }
            }*/
            
            
            
            current = head;
            while (current){
                if (maxIntKey < current->getIntKey()){
                    maxIntKey = current->getIntKey();
                    temp = current;
                }
                current = current->getNext();
            }    //current в итоге здесь равен NULL
            for (current = head; current->getNext() != NULL; current = current->getNext()){}
            tail = current;            //current в итоге здесь равен последнему элементу
            if (temp == head){
                current = head;
                head = current->getNext();
                
                delete current;
            }
            else if(temp == tail){
                for (current = head; current->getNext()->getNext() != NULL; current = current->getNext()){}
                current->setNext(NULL);
                /*или 
                for (current = head; current->getNext()->getNext() != NULL; current = current->getNext()){}
                temp2=current;
                current=current->getNext();
                delete current;
                current=temp2;
                current->setNext(NULL);
                */
            }
            else {
                for (current = head; current->getNext() != temp; current = current->getNext()){}
                //temp2 = current->getNext();
                current->setNext(temp->getNext());
                //current = temp2;
                //delete current;
            }
            break;
//______________________________________________________________________________________________________________________________________
        }
    }
}
void MainClass::createList(/*int n*/){
    /*current = new MainClass;

    std::cout<< "Key? ";  //ввод первого эл-та
    std::cin >> key;
    current->setKey(key);
    current->setNumber(0);
    current->setHead(current);

    for (int i = 0; i < n - 1; i++)
    {
        current->setNext(new MainClass);
        current->current->getNext();
        std::cout << "Key? ";
        std::cin >> key;
        current->setKey(key);
        current->setNumber(i + 1);
    }
    current->setNext(NULL);
    
    //tail = current;*/          
    char* key = new char[20];
    int intKey;      
    bool first = true;

    for (;;){
        std::cout << "charKey is?\t";
        std::cin >> key;
        if (!strcmp(key, "q")){
            break;
        }
        std::cout << "intKey is?\t";
        std::cin >> intKey;
        current = new MainClass;
        current->setKey(key);
        current->setIntKey(intKey);
        current->setNumber(counter);
        if (first == true)
        {
            head = current;
        }
        if (prev != NULL)
            prev->setNext(current);
        prev = current;

        first = false;
        counter++;
    }
}

MainClass.h
Код

class MainClass{        
    int number;
    int intKey;
    char* key;
    MainClass* next;
public:
    static MainClass* current;
    static MainClass* head;
    static MainClass* tail;
    static MainClass* prev;
    static int counter;

    MainClass();
    ~MainClass();
    int getNumber();
    void setNumber(int number);
    char* getKey();
    void setKey(char* key);
    int getIntKey();
    void setIntKey(int intKey);
    MainClass* getNext();
    void setNext(MainClass* next);

    void menu();
    void main();
    void createList(/*int n*/);
};            


start.cpp
Код
#include "MainClass.h"
#include <conio.h>
#include <iostream>
void main()
{
    MainClass* mainClassObject = new MainClass;
    mainClassObject->main();
}

PM MAIL   Вверх
sQu1rr
Дата 8.10.2014, 21:39 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Опытный
**


Профиль
Группа: Участник
Сообщений: 597
Регистрация: 11.11.2008
Где: london

Репутация: 3
Всего: 13



Можно ли поинтересоваться, что принимает автор?
1. кол-во new не соответсвует кол-ву delete
2. while(!current == NULL) вау! пусть даже это и работает...
3. половина кода либо лишняя либо бесмысленная
4. что вообще происходит?

Уберите пожалуйста все лишнее, абстрагируйте в функции
1. функция которая делает лист
2. функция которая добавляет элемент
3. функция которая убирает элемент
без всяких там меню и так далее, и выложите этот код, тогда разберемся в чем у вас проблема (желательно что бы вы написали эту с нуля, продумывая что вы пишете). И не нужен закомментированый код.
PM MAIL Skype GTalk   Вверх
lionwine
Дата 9.10.2014, 16:22 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Новичок



Профиль
Группа: Участник
Сообщений: 2
Регистрация: 8.10.2014

Репутация: нет
Всего: нет



Автор давно на кокаине и грибах, не удивляйтесь и, пожалуйста, распишите подробнее, что значит кол-во new не соответствует delete. Я удаляю только один элемент head. Остальное можно дописать. Но даже если не удалять а исключать из цепочки - все равно не работает. И что плохого в while. Проходится по списку

Это сообщение отредактировал(а) lionwine - 9.10.2014, 16:24
PM MAIL   Вверх
baldina
Дата 9.10.2014, 16:50 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Эксперт
****


Профиль
Группа: Завсегдатай
Сообщений: 3433
Регистрация: 5.12.2007
Где: Москва

Репутация: 32
Всего: 101



lionwine, отделите мух от котлет
узел списка
Код

struct Node {
  int key_;
  Node *next_;
  Node (int key, Node*next=0):key_(key),next_(next){}
};

список
Код

class List {
  Node *head_;
  public:
    List () : head_(0) {}
    ~List () {
       while (!empty()) removeTop ();
    }
   bool empty () const { return head_==0; }
   const Node *head () const { return head_; }
   void insert (int key) {
      head_ = new Node (key, head_);
   }
   void removeTop () {
      if (!empty()) {
        Node *newHead = head_->next_;
        delete head_;
        head_ = newHead;
      }
   }
};

основная программа
Код

void print (const List& list) {
  for (const Node *p=list.head(); p!=0; p=p->next_)
    cout << p->key_ << endl;
  cout << endl;
}
int main () {
  List l;
  for (int i=0; i < 5; ++i)
    l.insert(i);
  print (l);
  l.removeTop();
  l.removeTop();
  print (l);
}

PM MAIL   Вверх
sQu1rr
Дата 9.10.2014, 17:49 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Опытный
**


Профиль
Группа: Участник
Сообщений: 597
Регистрация: 11.11.2008
Где: london

Репутация: 3
Всего: 13



Цитата(lionwine @  9.10.2014,  16:22 Найти цитируемый пост)
что значит кол-во new не соответствует delete

Например тут
Код

char* key = new char[20];

создаете, а где удаляете? memory leak
Или тут
Код

MainClass* temp = new MainClass; // зачем new MainClass если потом всеравно приравниваете другое значение (без удаления прерыдущего)
MainClass* temp2 = new MainClass; // ^
MainClass* lastEven = new MainClass; // вообще не используете



Цитата(lionwine @  9.10.2014,  16:22 Найти цитируемый пост)
Я удаляю только один элемент head. Остальное можно дописать. Но даже если не удалять а исключать из цепочки - все равно не работает.

Не правильно выразился, мой комментарий был по коду а не кокретно по функции удаления (точнее куску кода ответсвенного за удаления)


Цитата(lionwine @  9.10.2014,  16:22 Найти цитируемый пост)
 И что плохого в while.

Запись плохая. вы "отрицаете указатель", что впринципе будет работать, но вводит в заблуждения, так как переменная может быть не указателем (если смотришь конкретный фрагмент кода), а операция ! может быть переопределена для класса во что то другое. Плюс, в С++ не используется NULL. тут где то был уже пост почему. либо 0 либо nullptr. Да и к тому же есть хорошее правило, там где можно записать if/while(pointer) не нужно писать if/while(pointer ==/!= nullptr) - много букаф
PM MAIL Skype GTalk   Вверх
  
Ответ в темуСоздание новой темы Создание опроса
Правила форума "С++:Общие вопросы"
Earnest Daevaorn

Добро пожаловать!

  • Черновик стандарта C++ (за октябрь 2005) можно скачать с этого сайта. Прямая ссылка на файл черновика(4.4мб).
  • Черновик стандарта C (за сентябрь 2005) можно скачать с этого сайта. Прямая ссылка на файл черновика (3.4мб).
  • Прежде чем задать вопрос, прочтите это и/или это!
  • Здесь хранится весь мировой запас ссылок на документы, связанные с C++ :)
  • Не брезгуйте пользоваться тегами [code=cpp][/code].
  • Пожалуйста, не просите написать за вас программы в этом разделе - для этого существует "Центр Помощи".
  • C++ FAQ

Если Вам понравилась атмосфера форума, заходите к нам чаще! С уважением, Earnest Daevaorn

 
0 Пользователей читают эту тему (0 Гостей и 0 Скрытых Пользователей)
0 Пользователей:
« Предыдущая тема | C/C++: Общие вопросы | Следующая тема »


 




[ Время генерации скрипта: 0.0820 ]   [ Использовано запросов: 22 ]   [ GZIP включён ]


Реклама на сайте     Информационное спонсорство

 
По вопросам размещения рекламы пишите на vladimir(sobaka)vingrad.ru
Отказ от ответственности     Powered by Invision Power Board(R) 1.3 © 2003  IPS, Inc.