Ok i'm trying to build a header file which then i can include it for programs that use singly linked lists but somthing is fishy here...:

here's the code

#include <iostream.h>

struct nod
{
	int info;
	nod* next_adr;};

void add(nod* &v, nod* &sf, int val)
{
	nod *c;
	if(v==0) //if list empty
	{
			v=new nod;
			v->info=val;
			v->next_adr=0;
			sf=v;
		}
	else
	{
		c=new nod;
		sf->next_adr=c;
		c->info=val;
		c->next_adr=0;
		sf=c;
	}
}

void insert_after(nod* v, nod*& sf, int val, int val1)
{
	nod* c=v,*d;
	while(c->info!=val) c=c->next_adr;
	d=new nod;
	d->info=val1; //the member _info_ of the node represented by _d_ takes the value of _val1_
	d->next_adr=c->next_adr;
	if(d->next_adr==0) sf=d;
}

void insert_before(nod* &v, int val, int val1)
{
	nod* c,* d;
	if(v->info==val)
	{
		d=new nod;
		d->info=val1;
		d->next_adr=v;
		v=d;
	}
	else
	{
		c=v;
		while(c->next_adr->info!=val)
			c=c->next_adr;
		d=new nod;
		d->info=val1;
		d->next_adr=c->next_adr;
		c->next_adr=d;
	}
}

void _delete(nod* &v, nod* &sf, int val)
{
	nod *c,*man;
	if(v->info==val)
	{
		man=v;
		v=v->next_adr;
	}
	else
	{
		c=v;
		while(c->next_adr->info!=val) c=c->next_adr;
		man=c->next_adr;
		c->next_adr=man->next_adr;
		if(man==sf) sf=c;
	}
	delete man;
}

void list_it(nod* v)
{
	nod* c=v;
	while(c)
	{
		cout<<c->info<<endl;
		c=c->next_adr;
	}
	cout<<endl;
}

and here's the program which tests these functions:

#include <liste.h>
#include <conio.h>

nod* v,* sf;

void main()
{
	clrscr();
	
	int i;
	for(i=1;i<=10;i++) add(v,sf,i);
	list_it(v);
	
	insert_after(v,sf,7,11);
	insert_after(v,sf,10,12);
	insert_after(v,sf,1,13);
	list_it(v);

	/// PROBLEM: There are no changes made

	insert_before(v,13,14);
	insert_before(v,1,15);
	list_it(v);
	
            /// PROBLEM: Program enters in an infinite loop and when breaked points me to "while(c->next_adr->info!=val)" @ insert_before() function in the header file
	_delete(v,sf,15);
	_delete(v,sf,13);
	_delete(v,sf,12);
	list_it(v);
	
            /// PROBLEM: same problem as before except this time points me to the while in the _delete() function
	getch();
}

solved :) the bug was in insert_after() ... i forgot to link the node that has the value val to the new node...

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.