Форум: Форум C++Разное
Новые темы: 00
C++. Мастер-класс в задачах и примерах. Авторы: Кузнецов М.В., Симдянов И.В. PHP 5/6. В подлиннике. Авторы: Кузнецов М.В., Симдянов И.В. Самоучитель MySQL 5. Авторы: Кузнецов М.В., Симдянов И.В. PHP на примерах (2 издание). Авторы: Кузнецов М.В., Симдянов И.В. PHP Puzzles. Авторы: Кузнецов М.В., Симдянов И.В.
ВСЕ НАШИ КНИГИ
Консультационный центр SoftTime

Форум C++

Выбрать другой форум

 

Здравствуйте, Посетитель!

вид форума:
Линейный форум Структурный форум

тема: двусвязные списки
 
 автор: AI\EKCAH^P   (04.06.2009 в 17:20)   письмо автору
 
 

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

Разработать программу для создания и работы с двусвязным списком, состоящим из структур. Для работы со списком создать меню со следующими пунктами:

1. Создание списка.
2. Просмотр списка.
3. Добавление в конец списка новой структуры.
4. удаление записи.
5. Выход.
Структура содержит название, цену, количество товара. Удалить из списка заданный товар.


#include<string.h>
#include<conio.h>
#include<io.h>
struct tov{
   char nazvanie[10];
   float cena;
   int kol;
   tov * nextElement;
   tov * lastElement;
};
//=======================================
tov * firstElement,   //первый
 * endElement,     //последний
 * currentElement, //текущий
 * nextElement,    //следующий
 * lastElement,    //предыдущий
 * tempElement;
int allElement=0;
FILE *save; 
//=======================================
void Menu(void);
void sozdanie_SP(void);
void prosmotr_SP();
void dobavlenie_SP();
void udalenie_EL();

int main(){
firstElement=0;
endElement=0;
Menu();
getche();
return 0;
 } 
 //===================  для ввода данных ===================
void enterElement(tov * element){ 
    printf(" vvedite nazvanie tovara  : ");
    scanf("%s",&element->nazvanie);
    printf(" vvedite cenu tovara  : ");
    scanf("%f",&element->cena);
    printf(" vvedite kolichestvo tovara  : ");
    scanf("%d",&element->kol);
    }
void sozdanie_SP(void){
tov * newElement;     //новый
do{
allElement++;
newElement = new tov;
enterElement(newElement);
if (firstElement!=0){
newElement->nextElement=firstElement;
firstElement->lastElement=newElement;
firstElement=newElement;
else firstElement=endElement=newElement;
}while(getche()!=27);
newElement->lastElement=endElement;
endElement->nextElement=newElement;
Menu();
 }  
 //============================== Удаление одной записи ===================================
void udalenie_EL(tov * delRec){
delRec->lastElement->nextElement=delRec->nextElement;
delRec->nextElement->lastElement=delRec->lastElement;
delete delRec;
}
 //============================== Добавление записи ===================================
void dobavlenie_SP(tov * lastRec, tov * nextRec){
    tov *tempLast=lastRec;
    tov *tempNext=nextRec;
    do{

allElement++;
    tov * newElement;
        newElement = new tov;
        enterElement(newElement);
        newElement->lastElement=lastRec;
        newElement->nextElement=nextRec;
        lastRec->nextElement=newElement;
        nextRec->lastElement=newElement;
        lastRec=newElement;
}while(getche()!=27);


//============================== Создание меню ===================================
void Menu(void) {


printf(" MENU \n");

printf(" F1 - VVEDITE NAZVANIE TOVARA                \n");
printf(" F2 - PROSMOTR                               \n");
printf(" F3 - DOBAVLENIE                             \n");
printf(" Del - UDALENIE                              \n");
printf(" Esc - VYHOD                                 \n");
switch (getch()){
  case 59: sozdanie_SP();break;
case 60: prosmotr_SP();break;
case 61: prosmotr_SP();break;
case 62: dobavlenie_SP();break;
case 63: udalenie_EL();break;
case 27: break;
defaultMenu();

}
}

  Ответить  
 
 автор: GeorgeIV   (05.06.2009 в 10:50)   письмо автору
 
   для: AI\EKCAH^P   (04.06.2009 в 17:20)
 

Мне кажется структура не совсем верна, двусвязные списки предполагают ссылку на предыдущий и последующий элемент в списке. Признаком первого элемента служит нулевая ссылка на предыдущий, признаком последнего - нулевая ссылка на последующий или, как вариант, ссылка на элемент со всеми нулями.
А вообще в STL есть стандартный шаблон "Список" (list), его и надо использовать

#include <list>

using namespace std;

....
list<tov>Spisok;

и т.д. Попробуй это вариант, там все функции есть - добавление, удаление, выборка элементов... При этом из структуры можно убрать ссылки на другие элементы, это будет во внутренней реализации стандартного списка.

  Ответить  
 
 автор: AI\EKCAH^P   (05.06.2009 в 20:08)   письмо автору
 
   для: GeorgeIV   (05.06.2009 в 10:50)
 

Программу переделал. Пункт в меню выбираю и все начинает мелькать.
Подскажите в чем дело.




#include <iostream.h>
#include <conio.h>
#include <stdio.h>
#include <list>


struct Item
{
    char itsName[10];
    int itsPrice;
    int itsCount;
    Item* itsNext;
    Item* itsPrev;
};

struct List
{
    Item* itsFirst;
  Item* itsLast;
};

void menu();
void AddItem(List&);
void DeleteItem(List&);
void PrintList(List&);
void CreateList (List*&);
List* theList = 0;

int main()

{
List* itsFirst=0;
List* itsLast=0;
   menu();
   getche();
   return 0;
}

void menu()
{
    bool quit = false;
    while (true)
    {
    int choice;
    printf(" ******* MENU *********** \n\n\n" );
    printf("(1) vvedite spisok \n" );
    printf"(2) prosmotr \n");
    printf("(3) dobavlenie \n");
    printf("(4) udalenie \n");
    printf("(5) vyhod \n" );
    
    scanf(" ",choice);
  
    switch (choice)
    {
    case(1):
        if (!theList)
        {
             CreateList (theList);
            theList->itsFirst = 0;
            theList->itsLast = 0;
            printf("the List has been created succesfully...");
        }
        else
            printf("the List is already created..." );
        break;
    case(2):
        if (theList)
            PrintList(*theList);
        else
            printf("the List is not created...");
        break;
    case(3):
        if (theList)
            AddItem(*theList);
        else
            printf("the List is not created...");
        break;
    case 4:
        if (theList)
            DeleteItem(*theList);
        else
            printf("the List is not created...");
        break;
    case(5):
        quit = true;
    }
    if (quit == true)
        break;
    }
}


void AddItem(List& theList)
{
    printf("*** dobavit' novuy tovar ***");
    printf("vvedite nazvanie: ");
    Item* newItem = new Item;
    gets(newItem->itsName);
    printf("vvedite cenu: ");
    scanf(" ",newItem->itsPrice);
    printf("vvedite kolichestvo: ");
    scanf(" ",newItem->itsCount);
    if (theList.itsLast)
    {
        theList.itsLast->itsNext = newItem;
        newItem->itsPrev = theList.itsLast;
    }
    else
    {
        theList.itsFirst = newItem;
        newItem->itsPrev = 0;
    }
    theList.itsLast = newItem;
    newItem->itsNext = 0;
    printf("*** item was added successfully ***");
}
void CreateList ( List*& pList)
{
    pList = new List;
  printf"*** vvedite tovar ***");
  printf("vvedite nazvanie: ");
    Item* newItem = new Item;
   scanf(" ", newItem->itsName);
  printf"vvedite cenu: " );
  printf(" ", newItem->itsPrice);
  printf("vvedite kolichestvo: ");
    scanf" ",newItem->itsCount);
    }
void PrintList(List& theList)
{
    printf("*** list content ***");
    Item* curItem = theList.itsFirst;
    while (curItem)
    {
        printf(curItem->itsName , " " ,curItem->itsPrice , "$ " ,curItem->itsCount ," ones." );
        curItem = curItem->itsNext;
    }
    printf("*** end ***" );
}

void DeleteItem(List& theList)
{
    Item* curItem = theList.itsFirst;
    int Pos;
    printf("Enter the position of deleted item: ");
    scanf(" ",Pos);
    printf(" ",Pos);
    for (int i=0; i<Pos ; i++) 
    {
        if (curItem)
            curItem = curItem->itsNext;
    }
    if (curItem && (Pos >= 0))
    {
        if (curItem->itsPrev)
        {
            curItem->itsPrev->itsNext = curItem->itsNext;
        }
        else
        {
            theList.itsFirst = curItem->itsNext;
        }
        if (curItem->itsNext)
        {
            curItem->itsNext->itsPrev = curItem->itsPrev;
        }
        else
        {
            theList.itsLast = curItem->itsPrev;
        }
        delete curItem;
        printf("Item № ", Pos ," has been deleted successfully..." ); 
    }
    else
        printf("Item № ", Pos , " not found..." );

}

  Ответить  
 
 автор: AI\EKCAH^P   (06.06.2009 в 12:20)   письмо автору
 
   для: AI\EKCAH^P   (05.06.2009 в 20:08)
 

Выбираю ввод списка,ввожу данные,а просмотр показывает,что ничего не ввел.
Может ввод списка не работает? Подскажите.

#include <iostream.h>
#include <conio.h>
#include <stdio.h>
#include <alloc.h>

struct Item
{
    char itsName[10];
    int itsPrice;
    int itsCount;
    Item* itsNext;
    Item* itsPrev;
};

struct List
{
    Item* itsFirst;
  Item* itsLast;
};

void menu();
void AddItem(List&);
void DeleteItem(List&);
void PrintList(List&);
void CreateList (List*&);
List* theList = 0;

int main()

{
List* itsFirst=0;
List* itsLast=0;
   menu();
   getche();
   return 0;
}

void menu()
{
    bool quit = false;
    while (true)
    {
    int choice;
    printf("\n ******* MENU *********** \n" );
    printf("(1) vvedite spisok \n" );
    printf"(2) prosmotr \n");
    printf("(3) dobavlenie \n");
    printf("(4) udalenie \n");
    printf("(5) vyhod \n" );
    
    scanf("%d",&choice);
  
    switch (choice)
    {
    case(1):
        if (!theList)
        {
             CreateList (theList);
            theList->itsFirst = 0;
            theList->itsLast = 0;
            printf(" the List has been created succesfully... \n");
        }
        else
            printf(" the List is already created...\n" );
        break;
    case(2):
        if (theList)
            PrintList(*theList);
        else
            printf(" the List is not created...\n");
        break;
    case(3):
        if (theList)
            AddItem(*theList);
        else
            printf(" the List is not created...\n");
        break;
    case 4:
        if (theList)
            DeleteItem(*theList);
        else
            printf(" the List is not created... \n");
        break;
    case(5):
        quit = true;
    }
    if (quit == true)
        break;
    }
}


void AddItem(List& theList)
{
    printf("\n *** dobavit' novuy tovar *** \n");
    printf(" vvedite nazvanie: ");
    Item* newItem = new Item;
    scanf("%s",&newItem->itsName);
    printf(" vvedite cenu: ");
    scanf("%f",&newItem->itsPrice);
    printf(" vvedite kolichestvo: ");
    scanf("%d",&newItem->itsCount);
    if (theList.itsLast)
    {
        theList.itsLast->itsNext = newItem;
        newItem->itsPrev = theList.itsLast;
    }
    else
    {
        theList.itsFirst = newItem;
        newItem->itsPrev = 0;
    }
    theList.itsLast = newItem;
    newItem->itsNext = 0;
    printf("*** item was added successfully *** \n");
}
void CreateList (List*&)
{ Item* pList,* p;
Item* itsFirst;
Item* itsLast;
    pList = NULL;
    do {p=(Item*)malloc(sizeof(Item));
  printf"*** vvedite tovar *** \n");
  printf(" vvedite nazvanie: ");
    Item* newItem = new Item;
   scanf("%s", newItem->itsName);
  printf" vvedite cenu: " );
  scanf("%f", &newItem->itsPrice);
  printf(" vvedite kolichestvo: ");
    scanf"%d",&newItem->itsCount);
    p->itsPrev=pList;
    if (pList != NULL)
    pList->itsNext=p;
    else
    itsFirst=p;
    pList=p;
    puts(" Zakonchit' - <esc>"
);
    }
 while (getch()!=27);
    itsLast=p;
    itsLast->itsNext=NULL;
    }
void PrintList(List& theList)
{
    printf("\n *** prosmotr spiska *** \n");
    Item* curItem = theList.itsFirst;
    while (curItem)
    {
        printf("%s\n",curItem->itsName);
        printf("%f\n",&curItem->itsPrice);
        printf("%d\n",&curItem->itsCount);
        curItem = curItem->itsNext;
    }
    printf("\n *** end *** \n" );
}

void DeleteItem(List& theList)
{
    Item* curItem = theList.itsFirst;
    int Pos;
    printf" Enter the position of deleted item: \n");
    scanf("%d",Pos);
    printf("%d",Pos);
    for (int i=0; i<Pos ; i++) 
    {
        if (curItem)
            curItem = curItem->itsNext;
    }
    if (curItem && (Pos >= 0))
    {
        if (curItem->itsPrev)
        {
            curItem->itsPrev->itsNext = curItem->itsNext;
        }
        else
        {
            theList.itsFirst = curItem->itsNext;
        }
        if (curItem->itsNext)
        {
            curItem->itsNext->itsPrev = curItem->itsPrev;
        }
        else
        {
            theList.itsLast = curItem->itsPrev;
        }
        delete curItem;
        printf("Item № ", Pos ," has been deleted successfully..." ); 
    }
    else
        printf("Item № ", Pos , " not found..." );

}

  Ответить  
 
 автор: AI\EKCAH^P   (06.06.2009 в 18:00)   письмо автору
 
   для: AI\EKCAH^P   (04.06.2009 в 17:20)
 

Всем спасибо! Работает!!!

  Ответить  
 
 автор: GeorgeIV   (08.06.2009 в 10:57)   письмо автору
 
   для: AI\EKCAH^P   (06.06.2009 в 18:00)
 

Главное вопрос задать:-) После этого обычно наступает прояснение. Я по выходным сюда не захожу, если что, на будущее....

  Ответить  
Rambler's Top100
вверх

Rambler's Top100 Яндекс.Метрика Яндекс цитирования