-
stack class
Ok, I've got my stack class I made, but as you know if I push 1,2,3 in a stack i would expect 3 to get popped out first right?
Mine doesn't!!! What's wrong?
Code:
template <class T>
class List
{
public:
List();
~List();
void Push(T); // Pushes i onto stack
T Pop(); // Pops top element from stack
int IsEmpty(); // returns 1 if empty; 0 if not empty;
int Contains(T);
private:
struct Node
{
T Item;
Node *Next;
};
Node *Head;
};
template <class T>
List<T>::List()
{
Head = 0;
}
template <class T>
List<T>::~List()
{
}
template <class T>
void List<T>::Push(T i) // Pushes i onto stack
{
Node *tmp, *curr;
//create new node and store integer
tmp = new Node;
tmp->Item = i;
tmp->Next = 0;
//add to top of stack if not empty
if(Head != 0)
{
curr = Head;
while(curr->Next)
curr = curr->Next;
curr->Next = tmp;
}
else
Head = tmp;
}
template <class T>
T List<T>::Pop() // Pops top element from stack
{
T tmp;
if(Head == 0) //nothing to pop!
return 0;
tmp = Head->Item;
Head = Head->Next;
return tmp;
}
template <class T>
int List<T>::IsEmpty() // returns 1 if empty; 0 if not empty;
{
if(Head == 0)
return 1;
return 0;
}
template <class T>
int List<T>::Contains(T i)
{
Node *curr;
if(Head->Item == i)
return 1;
else
{
curr = Head;
while(curr->Next)
{
if(curr->Item == i)
return 1;
else
curr = curr->Next;
}
}
return 0;
}
-
Code:
void List<T>::Push(T i) // Pushes i onto stack
{
Node *tmp, *curr;
//create new node and store integer
tmp = new Node;
tmp->Item = i;
tmp->Next = 0;
//add to top of stack if not empty
if(Head != 0)
{
curr = Head;
while(curr->Next)
curr = curr->Next;
curr->Next = tmp;
}
else
Head = tmp;
}
template <class T>
T List<T>::Pop() // Pops top element from stack
{
T tmp;
if(Head == 0) //nothing to pop!
return 0;
tmp = Head->Item;
Head = Head->Next;
return tmp;
}
You are adding new items to the list at the end while removing items from the beginning. You need to pick one or the other. Is it wise to have to go through the entire list to add or remove an item?
-
-