Traversing and Printing Linked List Data

Sep 16, 2024

Linked List Data Printing

Introduction

  • Presentation focuses on traversing a single linked list to print its data.
  • Assumptions:
    • A linked list is pre-existing.
    • The head pointer is referencing the first node.

Program Overview

  • Utilizes header files: stdio.h and stdlib.h.
  • Defines a struct node consisting of data and link parts.
  • Main function contains printData function, which prints linked list data.

Functionality

Function: printData

  • Parameter: head pointer
  • Purpose: Prints the data of each node in the linked list.

Execution Steps

  1. Check if Linked List is Empty:

    • If head is NULL, print "link list is empty."
  2. Initialize Pointer:

    • Define ptr as a pointer to struct node initialized to NULL.
    • Assign head to ptr.
  3. Traverse and Print Data:

    • While Loop: Continue looping while ptr is not NULL.
      • Print the data at the current node referenced by ptr.
      • Update ptr to point to the next node (ptr = ptr->link).

Example Execution

  • The linked list nodes have data: 45, 98, and 3.
    1. First Node:
      • Pointer (ptr) starts at address 1000.
      • Print data: 45.
      • Update ptr to the next node address (2000).
    2. Second Node:
      • Print data: 98.
      • Update ptr to the next node address (3000).
    3. Third Node:
      • Print data: 3.
      • Update ptr to NULL (end of list).
  • Exit loop when ptr is NULL.
  • Output: 45, 98, 3

Conclusion

  • Successfully demonstrated how to traverse a single linked list and print node data.
  • End of presentation.