Reputation: 13
Here is a function of a program I'm writing to get more familiar with nodes. I'm not sure if it is correct but essentially it check to see if the Node is Null if it is then it add the information to the code field and sets the pointer to NULL.
Otherwise it creates a new node and inserts the information into the code field and then points to the existing first node. I'm not sure how to change the header that's pointing to the original first node to point to the new node. The code is
typedef struct node {
LibraryCode location;
struct node *next;
} Node;
void insertFirstNode(LibraryCode code, Node **listPtr) {
Node *n=*listPtr;
Node *first;
if(n==NULL){
n=malloc(sizeof(Node));
n->location=code;
n->next=NULL;
} else
{
Node *first;
first->location=code;
first->next=n;
}
}
Upvotes: 0
Views: 368
Reputation:
The **listPtr is the address holding or to hold the head node of the list. If *listPtr == null then the list is empty I presume as the convention judging from what is provided. In any case we need to build a new Node for the LibraryCode provided. So a bit shortened (some error handling not spelled out)..
void insertFirstNode(LibraryCode code, Node **listPtr){
node = malloc( sizeof(Node) );
node->location = code;
node->next = *listPtr;
*listPtr = node;
}
Upvotes: 1
Reputation: 753870
You need to create the new node unconditionally (and set the location to the new value).
If there's already a list, you probably want to insert this node at the front of the list, and if there isn't a list, then this becomes the first node? Note the renamed function; it reflects the fact that a node will always be inserted.
void insertNode(LibraryCode code, Node **listPtr)
{
Node *new_node = malloc(sizeof(*new_node));
if (new_node == 0)
err_exit("Out of memory");
new_node->location = code;
new_node->next = *listPtr;
*listPtr = new_node;
}
If you want to insert at the end of the list if there is a list already, then:
void insertNode(LibraryCode code, Node **listPtr)
{
Node *new_node = malloc(sizeof(*new_node));
if (new_node == 0)
err_exit("Out of memory");
new_node->location = code;
new_node->next = NULL;
if (*listPtr == NULL)
*listPtr = new_node;
else
{
Node *node = *listPtr;
while (node->next != NULL)
node = node->next;
node->next = new_node;
}
}
If you want to bail out with an error if the list is already allocated, then you need to rethink your API design.
Upvotes: 2
Reputation: 360692
Basically, you've got two options. If the existing listPtr
is null, then you've got an empty list and just need to create its first entry. If listPtr is NOT null, then a list already exists, and you just need to stuff a new node into the beginning of the list.
So in pseudo-ish code:
if (listptr == null) {
... empty chain, create one
n = malloc(...);
n->location = code;
n->next = null;
} else {
... got an existing chain
n = malloc(...);
n->location = code;
n->next = listptr; // make previous top of chain be a child of new node}
}
return n;
Upvotes: 0