Linked list operations

The second section contains the two functions used to add and delete nodes from the linked list:

void deleteNode(struct Node **headNode, struct Node *delNode) {
// Base case:
if (*headNode == NULL || delNode == NULL) return;

// If node to be deleted is head node:
if (*headNode == delNode) *headNode = delNode->next;

// Change next only if node to be deleted is NOT the last node:
if (delNode->next != NULL) delNode->next->prev = delNode->prev;

// Change prev only if node to be deleted is NOT the first node:
if (delNode->prev != NULL) delNode->prev->next = delNode->next;

// Finally, free the memory occupied by delNode:
free(delNode);
}

void appendNode(struct Node **headNode, int id, int categoryId,
float rawAmount, float cookedAmount) {
// 1. Allocate node:
struct Node *newNode = (struct Node *) malloc(sizeof(struct Node));
struct Node *last = *headNode; // Used in Step 5

// 2. Populate with data:
newNode->id = id;
newNode->categoryId = categoryId;
newNode->rawAmount = rawAmount;
newNode->cookedAmount = cookedAmount;

// 3. This new node is going to be the last node, so make next NULL:
newNode->next = NULL;

// 4. If the linked list is empty, then make the new node as head:
if (*headNode == NULL) {
newNode->prev = NULL;
*headNode = newNode;
return;
}

// 5. Otherwise, traverse till the last node:
while (last->next != NULL) {
last = last->next;
}

// 6. Change the next of last node:
last->next = newNode;

// 7. Make last node as previous of new node:
newNode->prev = last;
}

The comments within the code describe what's happening at each step. When we need to add a Node to the list, we have to allocate the memory taken up by the struct Node using malloc() and append it to the last node in the linked list. If we need to delete a node, we have to remove it from the linked list and deallocate the memory that the node was using by calling the free() function.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset