top of page
Writer's picturecompnomics

C Program to Declare a Singly Linked List


Here is a C program to declare a singly linked list:

#include <stdio.h>
#include <stdlib.h>

// Structure to represent a node in the linked list
typedef struct node {
  int data;
  struct node* next;
} Node;

// Function to create a new node
Node* createNode(int data) {
  Node* newNode = (Node*)malloc(sizeof(Node));
  newNode->data = data;
  newNode->next = NULL;
  return newNode;
}

// Function to declare (initialize) an empty linked list
Node* declareList() {
  return NULL; // An empty list is represented by a NULL head pointer
}

int main() {
  // Declare an empty list
  Node* head = declareList();

  // You can now add nodes to the list using functions like:
  Node* node1 = createNode(10);
  Node* node2 = createNode(20);
  node1->next = node2; // Connect node1 to node2

  printf("List declared successfully!\n");

  // Free memory allocated for nodes before program ends
  free(node1);
  free(node2);

  return 0;
}

Explanation:

  1. Node structure: Defines the structure of each node in the list, holding data and a pointer to the next node.

  2. createNode function: Allocates memory for a new node, initializes its data and next pointer, and returns the new node.

  3. declareList function: Initializes the head pointer of the list to NULL, signifying an empty list.

  4. main function:

  • Declares an empty list using declareList.

  • Creates two nodes using createNode.

  • Connects the nodes by setting node1->next to node2.

  • Prints a confirmation message.

  • Frees the memory allocated for the nodes before program termination to prevent memory leaks.


Remember that this program only declares and initializes an empty list. You can further extend it to include functions for adding, removing, traversing, and printing the list elements. In the Upcoming Post, we will discuss other functions fo the Linked List and will see how to implement them.

30 views0 comments

Comments

Rated 0 out of 5 stars.
No ratings yet

Add a rating
bottom of page