105 / 102 / 89
Регистрация: 18.05.2009
Сообщений: 201
1

Двусвязный список структур

04.06.2009, 17:12. Показов 5960. Ответов 21
Метки нет (Все метки)

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

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

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


C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
#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();
        
    }
}
0
Programming
Эксперт
94731 / 64177 / 26122
Регистрация: 12.04.2006
Сообщений: 116,782
04.06.2009, 17:12
Ответы с готовыми решениями:

Заменить массив структур на односвязный список, и на двусвязный список
Взять текст задания и заменить массив структур на односвязный список, и на двусвязный список ...

Двусвязный список из структур
Ребят, помогите, а то не могу пример откопилировать... typedef struct tag_lib { ...

Переделать двусвязный список в двусвязный кольцевой
Здравствуйте, у меня єсть двусвязный список однако он не кольцевой! как это запрограммировать? и...

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

21
692 / 383 / 51
Регистрация: 22.01.2009
Сообщений: 1,135
04.06.2009, 17:36 2
Почти вске функции принимают параметры... а вызываешь их без параметров:
C++
1
2
3
4
5
6
7
8
9
10
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();
                
        }
1
105 / 102 / 89
Регистрация: 18.05.2009
Сообщений: 201
06.06.2009, 12:24  [ТС] 3
Выбираю ввод списка,ввожу данные,а просмотр показывает,что ничего не ввел.
Может ввод списка не работает? Подскажите.

Код
#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..." );

}
0
692 / 383 / 51
Регистрация: 22.01.2009
Сообщений: 1,135
06.06.2009, 13:42 4
C++
1
void CreateList (List*&)
что это? как в функцию передается параметр????? и зачем это:
C++
1
CreateList (theList);
если с theList ничего не делается?
1
105 / 102 / 89
Регистрация: 18.05.2009
Сообщений: 201
06.06.2009, 13:58  [ТС] 5
Он мне ошибку выдает тогда // #include "backward_warning.h"
0
692 / 383 / 51
Регистрация: 22.01.2009
Сообщений: 1,135
06.06.2009, 14:19 6
А что это за файл backward_warning.h ? Подключаешь его где то?
0
105 / 102 / 89
Регистрация: 18.05.2009
Сообщений: 201
06.06.2009, 14:26  [ТС] 7
Я не знаю что это за файл.Как его подключить.Он пишет...
46 C:\Dev-Cpp\Dev-Cpp\include\c++\backward\alloc.h
In file included from C:/Dev-Cpp/Dev-Cpp/include/c++/backward/alloc.h
0
692 / 383 / 51
Регистрация: 22.01.2009
Сообщений: 1,135
06.06.2009, 14:30 8
C++
1
#include <alloc.h>
поменяй на
C++
1
#include <malloc.h>
1
105 / 102 / 89
Регистрация: 18.05.2009
Сообщений: 201
06.06.2009, 14:37  [ТС] 9
Пасибо,теперь ему это ненравиться Item* pList,* p;
это после void CreateList (List*&)
0
692 / 383 / 51
Регистрация: 22.01.2009
Сообщений: 1,135
06.06.2009, 15:01 10
А ошибки какие говорит?
0
105 / 102 / 89
Регистрация: 18.05.2009
Сообщений: 201
06.06.2009, 15:02  [ТС] 11
118 C:\Dev-Cpp\Dev-Cpp\KP4.cpp
variable or field `CreateList' declared void
0
692 / 383 / 51
Регистрация: 22.01.2009
Сообщений: 1,135
06.06.2009, 15:13 12
C++
1
CreateList (List*&)
переменную не передаешь?
0
105 / 102 / 89
Регистрация: 18.05.2009
Сообщений: 201
06.06.2009, 15:16  [ТС] 13
118 C:\Dev-Cpp\Dev-Cpp\KP4.cpp
variable or field `CreateList' declared void
0
692 / 383 / 51
Регистрация: 22.01.2009
Сообщений: 1,135
06.06.2009, 15:17 14
C++
1
CreateList (List*& theList)
может все таки так лучше?
0
105 / 102 / 89
Регистрация: 18.05.2009
Сообщений: 201
06.06.2009, 15:19  [ТС] 15
Спасибо друг! Информация вводится. Только теперь просмотрр и добавление не работает.(
0
692 / 383 / 51
Регистрация: 22.01.2009
Сообщений: 1,135
06.06.2009, 15:33 16
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
#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..." );
 
}
Посмотри.... там на самом деле CreateList не правильно работает.. а просмотр и добавление нормально.... если добавлять то выведет только то что добавил... без того что ввел при создании.
1
105 / 102 / 89
Регистрация: 18.05.2009
Сообщений: 201
06.06.2009, 17:17  [ТС] 17
Только вот при выводе он что-то левое выдает . Но список теперь создается и выводиться.
И удаление не работает.

Код
#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);
            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;
   theList->itsFirst = NULL;
   theList->itsLast = NULL;
   Item *p,*k=NULL;

   do
    {
    p = new Item;
  printf( "*** vvedite tovar *** \n");
  printf(" vvedite nazvanie: ");
   scanf("%s", p->itsName);
  printf( " vvedite cenu: " );
  scanf("%f", &p->itsPrice);
  printf(" vvedite kolichestvo: ");
    scanf( "%d",&p->itsCount);

    if(theList->itsFirst==NULL) theList->itsFirst = p;

    p->itsNext = NULL;
    if(k)
     {
      p->itsPrev = k;
      k->itsNext = p;
     }
     else
      {
       p->itsPrev = NULL;
      }

    k = p;

    puts(" Zakonchit' - <esc>");
    }
 while (getch()!=27);

    theList->itsLast=p;
}


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   %s   %f   %d ",curItem->itsName,&curItem->itsPrice,&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..." );

}
0
692 / 383 / 51
Регистрация: 22.01.2009
Сообщений: 1,135
06.06.2009, 17:37 18
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
#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);
            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("%d",&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;
   theList->itsFirst = NULL;
   theList->itsLast = NULL;
   Item *p,*k=NULL;
 
   do
    {
    p = new Item;
  printf( "*** vvedite tovar *** \n");
  printf(" vvedite nazvanie: ");
  scanf("%s", &p->itsName);
  printf( " vvedite cenu: " );
  scanf("%d", &p->itsPrice);
  printf(" vvedite kolichestvo: ");
  scanf( "%d",&p->itsCount);
 
    if(theList->itsFirst==NULL) theList->itsFirst = p;
 
    p->itsNext = NULL;
    if(k)
     {
      p->itsPrev = k;
      k->itsNext = p;
     }
     else
      {
       p->itsPrev = NULL;
      }
 
    k = p;
 
    puts(" Zakonchit' - <esc>");
    }
 while (getch()!=27);
 
    theList->itsLast=p;
}
 
 
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   %s   %d   %d ",curItem->itsName,curItem->itsPrice,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..." );
 
}
Странно... удаление вроде работает... я немного поправил .. выводит правильно
1
105 / 102 / 89
Регистрация: 18.05.2009
Сообщений: 201
06.06.2009, 18:15  [ТС] 19
Да. Все работает. Только вводишь на удаление,например, первую позицию,а он вторую удаляет( То есть на позицию больше.
0
692 / 383 / 51
Регистрация: 22.01.2009
Сообщений: 1,135
06.06.2009, 18:19 20
Все правильно.. нумерация с нуля начинается.
1
06.06.2009, 18:19
IT_Exp
Эксперт
87844 / 49110 / 22898
Регистрация: 17.06.2006
Сообщений: 92,604
06.06.2009, 18:19
Помогаю со студенческими работами здесь

Двусвязный список (в конец двусвязного списка добавить другой список)
здравствуйте, подскажите пожалуйста, как в конец двусвязного списка добавить другой список?

Составить двусвязный список на основе класса, объекты которого будут формировать этот список
Составить двусвязный список на основе класса, объекты которого будут формировать этот список. В...

Создать двусвязный список групп факультета, где каждая группа представляет собой односвязный список студентов
Задание: создайте двусвязный список групп факультета. Каждая группа представляет собой односвязный...

Преобразовать односвязный список в двусвязный список
Доброго времени суток! Помогите, пожалуйста, преобразовать программу из односвязного списка в...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
20
Ответ Создать тему
Опции темы

КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2024, CyberForum.ru