I have been reading about pointers in C and I thought implementing a linked list would be a good exercise to test my knowledge.
Below is my code and it is 100% functional. All I am looking for is some criticism, such as how to make the functions more efficient or defining *pointerToLinkedList in a better spot.
#include <stdio.h>
#include <stdlib.h>
//Structure represents a node of a Linked List
struct node {
int data;
struct node* link;
};
//Pointer to the head node
struct node *pointerToLinkedList = NULL;
//Function inserts a new node at the beginning of the linked list
void insertNodeBeginning(int aData){
//pointer to the new node
struct node *newNode = (struct node*) malloc(sizeof(struct node));
//fill in data in new node
newNode->data = aData;
//point new node to the previous head (now second node in linked list)
newNode->link = pointerToLinkedList;
//adjust pointerToLinkedList accordingly with the new head
pointerToLinkedList = newNode;
}
//Function inserts a new node at the end of the linked list
void insertNodeEnd(int aData){
//pointer to the new node
struct node *newNode = (struct node*) malloc(sizeof(struct node));
//fill in data in new node
newNode->data = aData;
//point new node to NULL, because its last node in list
newNode->link = NULL;
//link second last node to the newly created last node of the linked list
//start at beginning of list
struct node *secondLastNode = pointerToLinkedList;
//loop until it becomes second last
while(secondLastNode->link != NULL){
secondLastNode = secondLastNode->link;
}
//actual linking
secondLastNode->link = newNode;
}
//Function deletes node at the beginning of the linked list
void deleteHead(){
//get reference of the head that will be deleted
struct node *temp = pointerToLinkedList;
//adjust pointerToLinkedList to the new head (previously the second node)
pointerToLinkedList = pointerToLinkedList->link;
//free memory of the old head
free(temp);
}
//Function deletes node at the end of the linked list
void deleteTail(){
//get reference of the head to iterate through linked list
struct node *temp = pointerToLinkedList;
struct node *newTail;
//iterate through linked list
while(temp->link != NULL){
newTail = temp;
temp = temp->link;
}
//free memory of old tail
free(newTail->link);
//adjust the new tail and point it to NULL
newTail->link = NULL;
}
Two more things apart from the criticism:
Am I using the
free()function properly? Is the structure actually being removed from the dynamic memory?What other functions apart from the four currently installed, would you recommend to implement as an exercise?