I've got a project that requires the user to input a capacitor's ID and its corresponding capacitance. The user can add the capacitor at the beginning or end of the list. But, I'm having trouble figuring out how to put it at the end of the list.

while( currentPtr != NULL)
{
	//Validate there aren't duplicate identifiers
	if (newPtr -> capacitor_id == currentPtr -> capacitor_id)
	{
		fprintf(stderr, "ID USED: Capacitors must have unique identification numbers.");
		return; //Silent return to main
	}
	
	currentPtr = currentPtr -> next;	//Move to the next ptr
}

currentPtr = newPtr;

The while loop loops through the existing linked list until it reaches the end of the list which has a dummy NULL value. This works as expected but it does not add the capacitor to the list.

Note:
--newPtr is a pointer that points to the structure capacitor. It holds both the ID and capacitance.

Any ideas would be greatly appreciated! :)

Thanks!

The while loop is incorrect -- make sure currentPtr != NULL before this loop starts!

while( currentPtr->next != NULL)
{
  // blabla
}
currentPtr->next = newPtr;

I got the program to finally work but there wasn't a problem with the while loop. I had entered a line of code that set the currentPtr to previousPtr. Then the currentPtr was incremented by one memory address (not contiguous).

Once the while loop reached the "dummmy NULL pointer" the program kicks out and goes to the if block that follows. This block checks to see if the previousPtr is NULL. If not then move to the next location and add the information. Then proceed to the next location and make that the new dummy pointer.

I'm curious as to what you meant by the problem with my while loop. Did you have an idea that might of been easier?

Thanks for your help!

>>I'm curious as to what you meant by the problem with my while loop. Did you have an idea that might of been easier?

Yes -- its in the code snippet I posted.

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.