Inserting a Node in Linked List

Sep 16, 2024

Lecture Notes: Inserting a Node at the End of a Single Linked List

Overview

  • Objective: Learn how to insert a node at the end of a singly linked list.
  • Initial Setup: Assume an existing linked list with a head pointer pointing to the first node.

Key Concepts

Node Insertion Process

  • Node and Address: Assume the new node to be inserted has an address 4000.
  • Pointer Setup:
    • temp pointer contains the address 4000.
    • ptr pointer is used to traverse the list starting from the head.

Traversing the List

  • Traverse the list using ptr until the end (last node) is reached.
  • Update the link part of the end node with the new node's address using the line ptr->link = temp:
    • This makes the new node the end node.

Program Structure

  • Main Function: Focuses on calling addAtEnd function to add a node at the end.
  • Function Parameters:
    • head: Pointer to the first node.
    • data: Data part of the new node.

Function Explanation: addAtEnd

Function Components

  • Parameters: struct node *head, int data
  • Pointers Used:
    • ptr: To traverse and reach the end of the list.
    • temp: To store the new node's address.

Steps in addAtEnd Function

  1. Assign Head to ptr: Initial traversal setup.
  2. Create New Node:
    • Allocate memory.
    • Assign data to the new node (data = 67).
    • Initialize link part to NULL.
  3. Traverse List:
    • Use while (ptr->link != NULL) to reach the last node.
    • Update ptr to point to the next node (ptr = ptr->link).
  4. Insert Node:
    • After exiting loop, update last node's link with new node's address (ptr->link = temp).

Important Concepts

  • Traversal Condition: Use ptr->link != NULL instead of ptr != NULL to stop at the last node, allowing for link update without setting it to NULL.

Conclusion

  • The function effectively adds a new node at the end of a singly linked list.
  • Assumes existence of a head pointer to a linked list.
  • After execution, the node is added successfully at the end.

End of Presentation

Thank you for watching!