little_greg Posted October 11, 2010 Report Share Posted October 11, 2010 Не могу разобраться с оператором "last->next = node;" какую роль он играет в программе, как я понял - "last->next" указывает на следующий элемент после последнего, но зачем тогда в нем сохранять адрес элемента "node"? #ifndef MYLIST_H_#define MYLIST_H_template<class T> class List{ private: List* prev; List* next; List* first; //первый элемент List* last; //последний элемент List* node; //узел T val; int count; public: List() : prev(0), next(0), first(0), last(0), node(0), count(0) {} void add(); void print();};#endif #include "mylist.h"#include <iostream>using std::cin;using std::cout;template<class T>void List<T>::add(){ node = new List; T v; cin >> v; node->val = v; node->next = 0; if (!count) first = node; else last->next = node; last = node; count++;}template<class T>void List<T>::print(){ node = first; while (node) { cout << node->val << '\n'; node = node->next; }} Link to comment Share on other sites More sharing options...
mmap Posted October 12, 2010 Report Share Posted October 12, 2010 По воводу вашего вопроса - присвоение last->next = node; делается для того, чтобы для текущего последнего элемента списка указать что есть следующий элемент (чтобы он был виден при обходе в print). Код некорректен. 1) Нельзя отделять определения шаблонных классов от реализации. Если так делать, то всегда прийдётся включать как .h так .cpp файл. Иначе компилятор не сможет найти реализацию для конкретного шаблона. 2) Я бы не стал пихать все поля в один класс. Так, count, first и last - относятся ко всему списку, а next и prev - только к элементу списка. 3) Вывод вообще к списку не имеет никакого отношения, как и то, откуда получается элемент. 4) Есть std::list Вот исправленный, компилирующийся код. #ifndef LIST_H#define LIST_H#include <stddef.h>template<class T>class List{private:struct Node{ Node *prev; // Предыдущий элемент Node *next; // Следующий элемент T data; // Значение};Node *first; // Первый элементNode *last; // Последний элементsize_t total; // Число элементов в спискеpublic:List();void print() const;size_t size() const;void push_back(const T &val);};#include <iostream>using std::cout;using std::endl;template<class T>List<T>::List():first(NULL), last(NULL), total(0){}template<class T>void List<T>::push_back(const T &data){Node *node = new Node();node->data = data;node->next = NULL;if (this->last != NULL){ node->prev = this->last; this->last->next = node;}else{ node->prev = NULL; this->first = node;}this->last = node;total++;}template<class T>void List<T>::print() const{cout << "Printing list content" << endl;Node *node = this->first;while (node != NULL){ cout << node->data << endl; node = node->next;}}template<class T>size_t List<T>::size() const{return this->total;}#endif /* LIST_H */ Link to comment Share on other sites More sharing options...
little_greg Posted October 12, 2010 Author Report Share Posted October 12, 2010 спасибо Link to comment Share on other sites More sharing options...
Архимаг Posted November 14, 2010 Report Share Posted November 14, 2010 Нужна программа, которая подсчитывает двухбуквенные сочетания. Подскажите как реализовать ? Link to comment Share on other sites More sharing options...
Aleksa106 Posted November 14, 2010 Report Share Posted November 14, 2010 Нужна программа, которая подсчитывает двухбуквенные сочетания. Подскажите как реализовать ? посмотрите справку по теме "Регулярные выражения"... Link to comment Share on other sites More sharing options...
Recommended Posts
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now