I am beginner to coding and I started learning C recently.
I wrote this code myself after learning concepts recently. I need few suggestions which can optimize my code.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
typedef struct Node{
int data;
struct Node* next;
}
node;
//function to add node at the front
void push(node** head_ref, int new_data){
//allocate node
node* new_node = (node*)malloc(sizeof(node));
//put in new data
new_node->data = new_data;
//make new node as head
new_node->next = (*head_ref);
//move the head to new node
(*head_ref) = new_node;
}
//function to add node after a certain node
void insertAfter(node* prev_node,int new_data){
//check if previous node is null
if(prev_node == NULL){
printf("the given previous node cannot be NULL");
return;
}
//allocate node
node* new_node = (node*)malloc(sizeof(node));
//put in new data
new_node->data = new_data;
//Make next of new node as next of prev_node
new_node->next = prev_node->next;
//move the next of prev_node as new_node
prev_node->next = new_node;
}
//function to add a new node at end
void append(node** head_ref, int new_data){
//allocate data
node* new_node = (node*)malloc(sizeof(node));
node* last = *head_ref;
//put in the new data
new_node->data = new_data;
//new node is going to be last to make its next null
new_node->next = NULL;
//If the Linked List is empty, then make the new node as head
if(*head_ref == NULL){
*head_ref = new_node;
return;
}
//else move to last node
while(last != NULL){
last = last->next;
}
last->next = new_node;
return;
}
void printList(node* nodee)
{
while (nodee != NULL)
{
printf(" %d ", nodee->data);
nodee = nodee->next;
}
}
int main()
{
//Start with the empty list
struct Node* head = NULL;
// Insert 6. So linked list becomes 6->NULL
append(&head, 6);
// Insert 7 at the beginning. So linked list becomes 7->6->NULL
push(&head, 7);
// Insert 1 at the beginning. So linked list becomes 1->7->6->NULL
push(&head, 1);
// Insert 4 at the end. So linked list becomes 1->7->6->4->NULL
append(&head, 4);
// Insert 8, after 7. So linked list becomes 1->7->8->6->4->NULL
insertAfter(head->next, 8);
printf("\n Created Linked list is: ");
printList(head);
return 0;
}