C Program Find the Length of Linked List without Recursion

This C program allows you to find the length of a linked list, which is the number of nodes present in the list, without using recursion.

Problem Statement

You are given a linked list, and your task is to write a C program to calculate the length of the linked list without using recursion.

C Program Find the Length of Linked List without Recursion

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#define MAX_SIZE 100

void removeRepeatedWords(char *str) {
    char *words[MAX_SIZE];
    int count = 0;

    // Tokenize the string into words
    char *token = strtok(str, " ");
    while (token != NULL) {
        words[count++] = token;
        token = strtok(NULL, " ");
    }

    // Check for repeated words and remove them
    for (int i = 0; i < count; i++) {
        if (words[i] != NULL) {
            for (int j = i + 1; j < count; j++) {
                if (words[j] != NULL && strcmp(words[i], words[j]) == 0) {
                    free(words[j]);
                    words[j] = NULL;
                }
            }
        }
    }

    // Reconstruct the string without repeated words
    int len = 0;
    for (int i = 0; i < count; i++) {
        if (words[i] != NULL) {
            int wordLen = strlen(words[i]);
            memcpy(str + len, words[i], wordLen);
            len += wordLen;
            str[len++] = ' ';
            free(words[i]);
        }
    }
    str[len - 1] = '\0';  // Remove the trailing space
}

int main() {
    char str[MAX_SIZE];

    printf("Enter a string: ");
    fgets(str, sizeof(str), stdin);

    // Remove the newline character at the end of the input
    str[strcspn(str, "\n")] = '\0';

    removeRepeatedWords(str);

    printf("String after removing repeated words: %s\n", str);

    return 0;
}

How it Works

  1. The program begins by including the necessary header files: stdio.h for input/output functions, string.h for string manipulation functions, and stdlib.h for memory allocation functions.
  2. The MAX_SIZE constant is defined, which represents the maximum size of the input string.
  3. The removeRepeatedWords function is defined. This function takes a pointer to a character array (string) as its parameter.
  4. Inside the removeRepeatedWords function:
    • An array of character pointers called words is declared to store the individual words from the string.
    • An integer variable count is initialized to keep track of the number of words stored in the words array.
  5. The string is tokenized into words using the strtok function. The strtok function splits the input string based on a specified delimiter, which in this case is a space character (” “). Each word is then stored in the words array, and the count is incremented.
  6. The program iterates through the words array to check for repeated words. It compares each word with the remaining words in the array using the strcmp function.
    • If a duplicate word is found, the corresponding pointer in the words array is freed using the free function, and the pointer is set to NULL.
    • This step ensures that the duplicate word is removed from the array but doesn’t modify the original string.
  7. After removing the duplicate words, the program reconstructs the string without the repeated words. It uses the memcpy function to copy each non-null word from the words array to the original string (str), updating the len variable to keep track of the string length. A space character is added after each word to separate them.
  8. Once all the non-repeated words are copied, the trailing space character is replaced with a null character (‘\0’) to properly terminate the string.
  9. In the main function:
    • The user is prompted to enter a string.
    • The input string is read using fgets and stored in the str array.
    • The newline character at the end of the input string is removed by replacing it with a null character (‘\0’) using strcspn.
    • The removeRepeatedWords function is called to remove repeated words from the input string.
    • Finally, the resulting string after removing repeated words is printed as output.

Input /Output

C Program Find the Length of Linked List without Recursion

Explanation:

  • The linked list has 5 nodes, so the length of the list is 5.
  • The findLength function is called with the head of the list as an argument.
  • Inside the function, the while loop iterates through the linked list, incrementing the length variable by 1 for each node.
  • After traversing the entire list, the function returns the final value of length.
  • The main function captures the returned length and prints it to the console using printf, resulting in the output: “Length of the linked list is: 5”.

Share:

Leave A Reply

Your email address will not be published. Required fields are marked *

You May Also Like

This C program finds the Greatest Common Divisor (GCD) of two given numbers. Problem Statement Write a C program that...
This C program calculates the roots of a quadratic equation of the form ax^2 + bx + c = 0....
This C program finds the first and last occurrence of a target character in a given string and displays their...