The following code seems to work. I appreciate any comments you can make on how to improve it please. The tough part for me was treating the pointers to the list slightly differently from the pointers to each node. My thinking was that they are both of type struct entry. I think where things started to break was when I had to use each type to reference what they pointed to. That is the next pointer of each node vs. listPtr, and other pointers outside of given node. I think I need to do more of these problems to get used to how to access each type. Here is the code:
Code:
#include <stdio.h>
struct entry {
int value;
struct entry *next;
};
struct entry *findEntry ( struct entry *listPtr, int match)
{
while ( listPtr != (struct entry *) 0)
{
printf ("Here is the current value%i\n", listPtr->value);
if ( listPtr->value == match )
return (listPtr);
else
listPtr = listPtr->next;
}
return (struct entry *) 0;
}
void insertEntry ( struct entry *newNode, struct entry *targetPtr)
// This function inserts a node after the targe Node
{
// set the pointer inside of new object to point to what target node is pointting to right now
newNode->next = targetPtr->next;
printf("Here is what is in new node value%i\n Here is what is in targetNode value %i\n",newNode->next, targetPtr->next);
// Now move the pointer inside of target node, and point to new object
// keep in mind that targetPtr is a pointer pointing to the new node. It is not a node; rather a pointer to a node
targetPtr->next = newNode;
}
struct entry newNodef ()
{
struct entry node, *nodePtr;
int newValue;
printf("Please tell me what value you want to store in the new node\n");
scanf("%i", &newValue);
node.value = newValue;
return node;
}
int main (void)
{
struct entry *findEntry ( struct entry *listPtr, int match);
void insertEntry ( struct entry *newNode, struct entry *targetPtr);
struct entry newNodef ();
struct entry n1, n2, n3;
struct entry *listPtr, *targetPtr, *listStart = &n1;
int search;
n1.value = 100;
n1.next = &n2;
n2.value = 200;
n2.next = &n3;
n3.value =300;
n3.next = (struct entry *) 0;
struct entry tempNode = newNodef();
listPtr = &tempNode;
targetPtr = &n2;
insertEntry ( listPtr, targetPtr);
printf("Here is what the new node is pointing to now %i. \n", tempNode.next->value );
printf ("Enter value to locate: ");
scanf ("%i", &search);
listPtr = findEntry (listStart, search);
if ( listPtr != (struct entry *) 0)
printf ("Found %i.\n", listPtr->value);
else
printf ("Not found. \n");
return 0;
}