Sunday, July 12, 2009

C++ linked List?

I have an assignment that I am trying to do right now. In class we had to do a Stack using a push and pop function. Now my teacher wants us to convert it from a stack to a linked list. I was wondering if there is a easy way to do this or not? here is my stack Code


#include%26lt;iostream%26gt;


using namespace std;





template%26lt;typename T%26gt;


class Stack


{


public:


Stack();


bool push (T);


bool pop (T%26amp;);


bool isEmpty();


private:


T *a;


int tos,arraysize;


void expandArray();


};





template%26lt;typename T%26gt;


Stack%26lt;T%26gt;::Stack()


{


tos = -1;


arraysize = 2;


a = new T[arraysize];


}





template%26lt;typename T%26gt;


bool Stack%26lt;T%26gt;::push(T x)


{





tos++;





if (tos == arraysize)


{ expandArray();}





a[tos] = x;


return true;


template%26lt;typename T%26gt;


bool Stack%26lt;T%26gt;::pop(T %26amp;x)


{


if (isEmpty() == true)


{return false;}

C++ linked List?
A linked list just contains pointers to adjacent elements. Your push and pop methods will become add, and delete methods. You'll want to override the add method so you can either add it onto the end of the list (default), or add it at a specific position in the list, (such as beginning or middle, you'll pass a number representing the position).





Also, there are several types of linked lists. There are linear linked lists which has nodes that only point to the next node; double linked lists which has nodes that point to both previous and next; circular linked listsw which has nodes that are linked in a circle.





So, it depends on which type (I assume the simpler one, the linear linked list) is what you would shoot for.

birthday flowers

No comments:

Post a Comment