examples_from_lect: BadList.cpp

File BadList.cpp, 1.6 KB (added by Evgeny Linsky, 8 years ago)
Line 
1#include <stddef.h>
2
3class BadList {
4protected:
5        BadList *next;
6        int n;
7       
8public:
9        BadList(int first) {
10                n = first;
11                next = NULL;
12        }
13        virtual ~BadList() {
14                //?
15         }
16       
17        virtual void add(int value) {
18                BadList *current = this;
19                while ( current->next != NULL ) {
20                        current = current->next;
21                }
22                current->next = new BadList(value);
23        }
24       
25        size_t length() {
26                size_t l = 0;
27                BadList *current = this;
28                while ( current->next != NULL) {
29                        current = current->next;
30                        l++;
31                }
32                return l;
33        }
34};
35
36class BadDoubleList : public BadList {
37protected:
38        BadDoubleList *prev;
39       
40public:
41        BadDoubleList(int start) : BadList(start) {
42                prev = NULL;
43        }               
44       
45        virtual void add(int value) {
46                BadDoubleList *current = this;
47                while ( current->next != NULL ) {
48                        current = (BadDoubleList*) current->next;
49                }
50               current->next = new BadDoubleList(value);
51               ((BadDoubleList*) current->next)->prev = current;
52        }       
53       
54};     
55
56
57void fill(BadList *l, int value, size_t num) {
58        for(int i = 0; i < num; i++) {
59                l->add(value);
60        }
61}
62
63int main() {
64        BadList l(1);
65        BadDoubleList dl(1);
66       
67        fill(&l, 5, 5);
68        fill(&dl, 6, 6);
69        return 0;
70}