Wednesday, January 15, 2025
HomeProgrammingHow to Create a linked list in C

How to Create a linked list in C

Creating a linked list in C involves defining a structure for the nodes and implementing functions to manipulate the list, such as insertion, deletion, and traversal.

A linked list consists of nodes, where each node contains data and a pointer to the next node.

Steps to Create a Linked List:

1. Define the Node Structure:
Each node holds data and a pointer to the next node.
c
struct Node {
int data;
struct Node* next;
};

See also  What is the entrySet() method in Java's HashMap?

2. Create a New Node:
Allocate memory for a new node and initialize it.
c
struct Node* newNode(int data) {
struct Node* node = (struct Node*)malloc(sizeof(struct Node));
node->data = data;
node->next = NULL;
return node;
}

3. Insert at the Beginning:
Insert a new node at the start of the list.
c
void insertAtBeginning(struct Node** head, int data) {
struct Node* node = newNode(data);
node->next = *head;
*head = node;
}

See also  How do I update a local repository with changes from a GitHub remote repository?

4. Traverse and Print the List:
c
void printList(struct Node* head) {
while (head != NULL) {
printf(“%d -> “, head->data);
head = head->next;
}
printf(“NULL\n”);
}

Example Usage:
c
int main() {
struct Node* head = NULL;
insertAtBeginning(&head, 10);
insertAtBeginning(&head, 20);
printList(head);
return 0;
}

See also  How to Call a Method in Java

This will create a simple linked list and print its contents.

RELATED ARTICLES
0 0 votes
Article Rating

Leave a Reply

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
- Advertisment -

Most Popular

Recent Comments

0
Would love your thoughts, please comment.x
()
x