sample programs
sample programs
h>
#include <stdlib.h>
if(head == NULL) {
printf("List is empty\n");
return;
}
printf("Nodes of singly linked list: \n");
while(current != NULL) {
//Prints each node by incrementing pointer
printf("%d ", current->data);
current = current->next;
}
printf("\n");
}
int main()
{
//Add nodes to the list
addNode(1);
addNode(2);
addNode(3);
addNode(4);
return 0;
}
The line of code struct node* newnode = (struct node*) malloc(sizeof(struct node)); is used
in C programming to allocate memory dynamically for a new node of a linked list (or any
similar data structure). Let's break it down:
: This declares a pointer named newnode that will point to a struct node. The struct node is
presumably a user-defined structure that you've defined elsewhere in your code.
:
- malloc is a standard library function that allocates a specified number of bytes in memory.
It returns a pointer to the beginning of the allocated memory block.
- sizeof(struct node) computes the size (in bytes) of the struct node. This ensures that the
correct amount of memory is allocated to hold a single instance of struct node.
: This is a type cast. malloc returns a pointer of type void*, which can point to any data type.
To make it explicit that the pointer returned by malloc should be treated as a pointer to
struct node, we cast it to (struct node*).
// // C Program for Implementation of Singly Linked List
#include <stdio.h>
#include <stdlib.h>
// Function to insert a new element at the beginning of the singly linked list
void insertAtFirst(struct Node** head, int data) {
struct Node* newNode = createNode(data);
newNode->next = *head;
*head = newNode;
}
// Function to insert a new element at the end of the singly linked list
void insertAtEnd(struct Node** head, int data) {
struct Node* newNode = createNode(data);
if (*head == NULL) {
*head = newNode;
return;
}
struct Node* temp = *head;
while (temp->next != NULL) {
temp = temp->next;
}
temp->next = newNode;
}
// Function to insert a new element at a specific position in the singly linked list
void insertAtPosition(struct Node** head, int data, int position) {
struct Node* newNode = createNode(data);
if (position == 0) {
insertAtFirst(head,data);
return;
}
struct Node* temp = *head;
for (int i = 0; temp != NULL && i < position - 1; i++) {
temp = temp->next;
}
if (temp == NULL) {
printf("Position out of range\n");
free(newNode);
return;
}
newNode->next = temp->next;
temp->next = newNode; }
// Function to delete the first node of the singly linked list
void deleteFromFirst(struct Node** head) {
if (*head == NULL) {
printf("List is empty\n");
return;
}
struct Node* temp = *head;
*head = temp->next;
free(temp);
}
// Driver Code
int main() {
struct Node* head = NULL;
insertAtFirst(&head, 10);
printf("Linked list after inserting the node:10 at the beginning \n");
print(head);
return 0;
}