In general, there is a question. I make a single linked list. Naturally, this is a class and structure. In general, I saw others, the function of adding an item, write through a new Item, I just declare the Item. It seems to be debugging everything plows, but when I call the output function, the values of the firstItem and lastItem pointer are lost ... Maybe someone can help? It seems that the usual declaration should also be allocated memory (Item itm;)
List.h
#pragma once class List { struct Item { int number; Item * next; }; int countAll; Item * firstItem = NULL; Item * lastItem = NULL; public: void AddLast(int); void RemoveLast(); void ShowAllElements(); void showItem(Item *); List(); ~List(); }; list.cpp
#include "stdafx.h" #include "List.h" #include <iostream> using namespace std; void List::AddLast(int n) { Item itm = { n, NULL }; /*itm->next = NULL; itm->number = n;*/ if (firstItem == lastItem) { firstItem = &itm; lastItem = firstItem->next; } else { lastItem = &itm; lastItem->next = itm.next; lastItem = lastItem->next; } } void List::RemoveLast() { Item * tmp; tmp = lastItem->next; delete lastItem; lastItem = tmp; } void List::ShowAllElements() { Item *next = firstItem->next; Item *itm = firstItem; while (next) { showItem(itm); itm = itm->next; next = itm->next; } } void List::showItem(Item * itm) { cout << "there is number: " << itm->number << endl; } List::List() { Item itm; this->firstItem = this->lastItem = &itm; } List::~List() { } main
// OneRootList.cpp: определяет точку входа для консольного приложения. // #include "stdafx.h" #include "List.h" #include <iostream> using namespace std; int main() { List list; list.AddLast(1); list.AddLast(1); list.ShowAllElements(); }