Data Structures (BCA) 3rd Sem Previous Year Solved Question Paper 2022

Practice Mode:
4.

Write an algorithm to find the number NUM of non-zero elements in a linked list.

Explanation

The number of non-zero elements in a linked list, you can traverse the linked list and count the elements that are not equal to zero. Here's a simple algorithm to achieve this:

Algorithm CountNonZeroElements(head):

Initialize a variable `count` to 0

Initialize a pointer `current` to the head of the linked list



while current is not null:

if current.data is not equal to 0:

Increment `count` by 1

Move `current` to the next node

 Return `count` as the number of non-zero elements

 

step-by-step explanation of the algorithm:

  1. Initialize a count variable to 0. This variable will keep track of the number of non-zero elements.

  2. Initialize a pointer current to the head of the linked list. This pointer will be used to traverse the linked list.

  3. Start a loop that continues until current reaches the end of the linked list (i.e., current becomes null).

  4. Inside the loop, check if the data in the current node (accessed as current.data) is not equal to zero. If it's not zero, increment the count variable by 1.

  5. Move the current pointer to the next node in the linked list to continue the traversal.

  6. Once the loop is complete, return the count variable, which will contain the number of non-zero elements in the linked list.