Форум программистов
 

Восстановите пароль или Зарегистрируйтесь на форуме, о проблемах и с заказом рекламы пишите сюда - alarforum@yandex.ru, проверяйте папку спам!

Вернуться   Форум программистов > C/C++ программирование > Общие вопросы C/C++
Регистрация

Восстановить пароль

Купить рекламу на форуме - 42 тыс руб за месяц

Ответ
 
Опции темы Поиск в этой теме
Старый 04.06.2009, 17:08   #1
ai\ekcah^p
Форумчанин
 
Аватар для ai\ekcah^p
 
Регистрация: 03.05.2009
Сообщений: 112
По умолчанию двусвязные списки

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

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

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;
		default: Menu();
		
	}
}
ai\ekcah^p вне форума Ответить с цитированием
Старый 04.06.2009, 17:29   #2
Sazary
В тени
Старожил
 
Аватар для Sazary
 
Регистрация: 19.12.2008
Сообщений: 5,788
По умолчанию

У вас функции объявлены без параметров:
Код:
void Menu(void);
	void sozdanie_SP(void);
	void prosmotr_SP();
	void dobavlenie_SP();
	void udalenie_EL();
Описываются с параметрами:
Код:
void udalenie_EL(tov * delRec)
Код:
void dobavlenie_SP(tov * lastRec, tov * nextRec){
а вызываются опять без них:
Код:
(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;
А функции prosmotr_SP() вообще нет.
Вполне очевидно, чтобы что-то понять, необходимо книги читать.
Не нужно плодить бессмысленных тем. Вас Поиск избавит от многих проблем.

___________________________________ ___________________________________ _______
[=Правила форума=]_____[Поиск]_____[Литература по С++]____[Литература. Паскаль]
Sazary вне форума Ответить с цитированием
Старый 05.06.2009, 19:59   #3
ai\ekcah^p
Форумчанин
 
Аватар для ai\ekcah^p
 
Регистрация: 03.05.2009
Сообщений: 112
По умолчанию

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

Код:
#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 вне форума Ответить с цитированием
Старый 05.06.2009, 20:19   #4
Sazary
В тени
Старожил
 
Аватар для Sazary
 
Регистрация: 19.12.2008
Сообщений: 5,788
По умолчанию

У вас в меню:
Код:
scanf(" ",choice);
не указан спецификатор:

Код:
scanf("%d",&choice);
То же самое и в других функциях.
Вполне очевидно, чтобы что-то понять, необходимо книги читать.
Не нужно плодить бессмысленных тем. Вас Поиск избавит от многих проблем.

___________________________________ ___________________________________ _______
[=Правила форума=]_____[Поиск]_____[Литература по С++]____[Литература. Паскаль]
Sazary вне форума Ответить с цитированием
Старый 06.06.2009, 12:31   #5
ai\ekcah^p
Форумчанин
 
Аватар для ai\ekcah^p
 
Регистрация: 03.05.2009
Сообщений: 112
По умолчанию

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

Код:
#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, 14:42   #6
Sazary
В тени
Старожил
 
Аватар для Sazary
 
Регистрация: 19.12.2008
Сообщений: 5,788
По умолчанию

Вы посылаете в функцию список:
Код:
  CreateList (theList);
но в самой функции он где?
Код:
void CreateList (List*&)
То есть после возвращения из функции, TheList не существует, а вы присваиваете его полям значения:
Код:
theList->itsFirst = 0;
            theList->itsLast = 0;
вот и вылетает.
Вполне очевидно, чтобы что-то понять, необходимо книги читать.
Не нужно плодить бессмысленных тем. Вас Поиск избавит от многих проблем.

___________________________________ ___________________________________ _______
[=Правила форума=]_____[Поиск]_____[Литература по С++]____[Литература. Паскаль]
Sazary вне форума Ответить с цитированием
Старый 06.06.2009, 14:46   #7
Timofey
 
Регистрация: 08.12.2008
Сообщений: 6
По умолчанию

List* itsFirst=0;
List* itsLast=0;
Тут идет переопределение типа указателей на итем на лист.Нужно менять лист на итем.
theList.itsLast -
Желательно во всех подобных конструкциях использовать конструкцию
theList->itsFirst
theList->itsLast
Если все это не поможет,то следует менять логику программы.
Поможем.
Timofey вне форума Ответить с цитированием
Старый 06.06.2009, 15:40   #8
ai\ekcah^p
Форумчанин
 
Аватар для ai\ekcah^p
 
Регистрация: 03.05.2009
Сообщений: 112
По умолчанию

Исправил. Теперь ввод работает,добавление работает,просмотр не работает. Только после добавления показывает добавленные товары.

Код:
#include <iostream>
#include <conio.h>
#include <stdio.h>
#include <malloc.h>
 
using namespace std;
 
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 = NULL; 
            theList->itsLast = NULL;
            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*& theList)
{
        theList = new List;
        Item* pList = new Item,* p;
        Item* itsFirst = new Item;
        Item* itsLast = new Item;
    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, 15:50   #9
ai\ekcah^p
Форумчанин
 
Аватар для ai\ekcah^p
 
Регистрация: 03.05.2009
Сообщений: 112
По умолчанию

Посмотрите.... там наверно CreateList не правильно работает.. а просмотр и добавление нормально.... если добавлять то выведет только то что добавил... без того что ввел при создании.
ai\ekcah^p вне форума Ответить с цитированием
Старый 06.06.2009, 16:15   #10
Timofey
 
Регистрация: 08.12.2008
Сообщений: 6
По умолчанию

Не смотря сразу скажу,что самое больное место в 2-х связных списках ,Это создание первого элемента,где конкретно инициализируется основная масса переменных и далее идет все от него.
Покажите последний обновленый код.
Если так void CreateList (List*& theList),лучше сделать void CreateList (List** theList),

то вызов будет CreateList (&theList);

Измените трактовку слова указатель на слово адресс и станет легче ориентироваться .

Последний раз редактировалось Timofey; 06.06.2009 в 16:52.
Timofey вне форума Ответить с цитированием
Ответ


Купить рекламу на форуме - 42 тыс руб за месяц



Похожие темы
Тема Автор Раздел Ответов Последнее сообщение
Списки C++ paladinn Помощь студентам 1 27.05.2009 12:31
Двусвязные списки Serp Помощь студентам 3 14.04.2009 16:13
списки Влдислаав3911 Паскаль, Turbo Pascal, PascalABC.NET 5 10.05.2008 17:35