C Linked List Operations 🎯

beginner
8 min

C Linked List Operations 🎯

Welcome to the fascinating world of C Linked Lists! In this comprehensive guide, we'll learn about the essential operations of a Linked List, one of the fundamental data structures used in C programming. By the end of this lesson, you'll be ready to create your own linked lists and apply them to various real-world projects. 💡 Pro Tip: Linked Lists are particularly useful when dealing with dynamic data structures!

Table of Contents

  1. Understanding Linked Lists
  2. Creating a Node
  3. Inserting a Node
  4. Deleting a Node
  5. Traversing a Linked List
  6. Quiz

Understanding Linked Lists 📝

A Linked List is a linear data structure where data is stored in nodes connected by pointers. Unlike arrays, the size of a Linked List can be dynamic as we can add or remove nodes as needed.


Creating a Node 📝

Each node in a Linked List consists of two parts: data and a pointer to the next node. Here's an example of how we can define a Node structure:

c
struct Node { int data; struct Node* next; };

In this example, int data represents the data stored in the node, and struct Node* next is a pointer to the next node.


Inserting a Node 📝

To insert a new node into a Linked List, we follow these steps:

  1. Allocate memory for a new node.
  2. Set the data field of the new node with the desired value.
  3. Set the next pointer of the new node to point to the head of the Linked List or the last node in case of insertion at the beginning or end, respectively.
c
struct Node* createNode(int data) { struct Node* newNode = (struct Node*)malloc(sizeof(struct Node)); newNode->data = data; newNode->next = NULL; return newNode; }

Deleting a Node 📝

Deleting a node from a Linked List involves finding the node to be deleted and adjusting the pointers accordingly. Here's a simple implementation for deleting a node with a specific value:

c
void deleteNode(struct Node** head, int key) { if (*head == NULL) return; struct Node *temp = *head, *prev; if (temp->data == key) { *head = temp->next; free(temp); return; } while (temp != NULL && temp->data != key) { prev = temp; temp = temp->next; } if (temp == NULL) return; prev->next = temp->next; free(temp); }

Traversing a Linked List 📝

Traversing a Linked List means iterating through each node in the list. This is useful for accessing or manipulating the data stored in the nodes.

c
void printList(struct Node* node) { while (node != NULL) { printf("%d -> ", node->data); node = node->next; } printf("NULL\n"); }

Quiz 📝

Quick Quiz
Question 1 of 1

Which of the following is NOT a part of a Linked List Node?