Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations bkrike on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

implementing a cirlce using pointers

Status
Not open for further replies.

jimberger

Programmer
Jul 5, 2001
222
GB
Hello all,

i am trying to implement a cirlcular data structure using pointers. I have defined a class called node and then declared a vector of type node. In the node i want a pointer to point to the next node, so for the last node the pointer should point to the first node to maintain a circular struture, however i am having difficulty in working out how to do this. Can anyone give me any ideas?
thanks for your time
jim
 
hi,

to deploy a circular management of objects by a vector,
may help you or not.
Your single item (class or simple structure) is done of
2 essential parts: the data and the pointer.
If you dont put these structs in an array, it can be easier
for you, insert and delete items in any points.

Each time you create a stucture you have to allocate
memory by new or malloc. The pointer of each str. points
to the next. Begin with an open chain (LIFO), then close it.

Follows a little example in wich the struct is:
loaded, printed, item-deleted, free memory


struct Item
{
int data;
struct Item * next ;
};

void PrintClosedCirc( struct Item * pStart )
{
struct Item *p ;
printf("-----\n" ) ;
p = pStart ;
do
{
printf("%d\n", p->data ) ;
p = p->next;
}
while( p != pStart ) ;
}

void Erase( struct Item * pStart, int x )
{
// this simple implem. assumes that
// item to del is not pStart pointed!

struct Item *p, *pPrev ;

p = pStart ;
do
{
pPrev = p ;
p = p->next;
}
while( p->data != x ) ;

pPrev->next = p->next ;
free( p ) ;
}


void Free( struct Item * pStart )
{
struct Item *p, *pPrev ;

p = pStart ;
do
{
pPrev = p ;
p = p->next;
free( pPrev ) ;
}
while( p != pStart ) ;
}


#define SIZE sizeof(struct Item)

main()
{
struct Item *p1, *p2, *pFirst ;
p1=(struct Item *) malloc( SIZE );
pFirst=p1;
p1->data=100;
p1->next=NULL;

for( int i=1; i<5 ; i++ )
{
p2 = (struct Item *)malloc(SIZE);
p2->data = 100+i ;
p2->next = p1 ;
p1 = p2 ;
}



while( p1 != NULL ) // print an open chain
{
printf(&quot;%d\n&quot;, p1->data ) ;
p1=p1->next;
}

pFirst->next = p2 ; // close chain

PrintClosedCirc( pFirst ) ;

Erase( pFirst, 102 ) ;

PrintClosedCirc( pFirst ) ;

Free( pFirst ) ;

}



BYE


P.S.: try to put all code in functions, improve Erase,
implement Insert, and after belive it in C++ with Class.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top