Hello there, I was just practicing my Linked Lists. I have come out with some code, works well with exception of the first element that I insert. Can anyone please tell me what I did wrong? So far this is my code:
Code:#include <iostream> using namespace std; template <class T> class Node { public: T * data; Node<T> * next; Node() { data = NULL; next = NULL; } Node(T * elem, Node<T> * tail) { data = elem; next = tail; } void printList() { Node<T> * current = this; while(current != NULL) { cout << current->data << endl; current= current->next; } } }; template <class T> class Stack { Node<T> * list; int count; public: Stack() { list = NULL; count = 0; } void push(T elem) { Node<T> * temp = new Node<T>(new T(elem), list); list = temp; delete(temp); count++; cout << "Count is now " << count << endl; } T * peek() { if(count > 0) return list->data; else throw (char*)"Cannot peek at an empty list!"; } T * pop() { if(count >= 0) { Node<T> * temp = list; list = list->next; count--; return(temp->data); } else throw (char*)"Cannot pop! List is empty!"; } void printList() { list->printList(); } int getCount(){ return count; } }; int main() { Stack<int> IntStack; IntStack.push(9999); IntStack.push(1); IntStack.push(2); IntStack.push(3); IntStack.push(4); IntStack.push(5); IntStack.push(6); IntStack.push(7); IntStack.push(8); IntStack.push(9); IntStack.push(10); int size = IntStack.getCount(); try{ for( int x = 0; x <= size; x++ ) cout << (int)IntStack.pop()<< endl; } catch(...) { cout << "Exception!" << endl; } return 0; }
and this was my output:
Why does it not display the first element???Code:Count is now 1 Count is now 2 Count is now 3 Count is now 4 Count is now 5 Count is now 6 Count is now 7 Count is now 8 Count is now 9 Count is now 10 Count is now 11 0 10 9 8 7 6 5 4 3 2 1 Process returned -1073741819 (0xC0000005) execution time : 6.343 s Press any key to continue.
Thanks in advance!



LinkBack URL
About LinkBacks


