Linkedlist part1

Linear Linked List: A Beginner's Guide

A Linear Linked List is a fundamental data structure in computer science. It consists of a sequence of nodes where each node contains data and a reference (or link) to the next node in the sequence.

Structure of a Linked List

Each node in a linked list has two parts:

  • Data – Stores the value
  • Next Pointer – Points to the next node

Basic Operations

  • Insertion
  • Deletion
  • Traversal
  • Searching

Example in C

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

struct Node* head = NULL;

Advantages

  • Dynamic size
  • Efficient insertion and deletion

Disadvantages

  • No random access
  • Extra memory for pointers

Conclusion

Linear linked lists are simple yet powerful. They are widely used in memory management, dynamic data structures, and many real-world applications.

// Node structure
struct Node {
  int data;
  struct Node* next;
};

// Insert at beginning
struct Node* insertAtBeginning(struct Node* head, int value) {
  struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
  newNode->data = value;
  newNode->next = head;
  return newNode;
}

// Insert at end
struct Node* insertAtEnd(struct Node* head, int value) {
  struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
  newNode->data = value;
  newNode->next = NULL;

  if (head == NULL) {
    return newNode;
  }

  struct Node* temp = head;
  while (temp->next != NULL) {
    temp = temp->next;
  }

  temp->next = newNode;
  return head;
}

Post a Comment

Previous Post Next Post