Write C Program For Finding The Length Of Loop In Linked List

Last Updated: 02-Apr-2023 15:08:05
108 Views
Summarize

Git is a distributed version control system DVCS designed for efficient source code management, suitable for both small and large projects. It allows multiple developers to work on a project simultaneously without overwriting changes, supporting collaborative work, continuous integration, and deployment. This Git and GitHub tutorial is designed for beginners to learn fundamentals and advanced concepts, including branching, pushing, merging conflicts, and essential Git commands. Prerequisites include familiarity with the command line interface CLI, a text editor, and basic programming concepts. Git was developed by Linus Torvalds for Linux kernel development and tracks changes, manages versions, and enables collaboration among developers. It provides a complete backup of project history in a repository. GitHub is a hosting service for Git repositories, facilitating project access, collaboration, and version control. The tutorial covers topics such as Git installation, repository creation, Git Bash usage, managing branches, resolving conflicts, and working with platforms like Bitbucket and GitHub. The text is a comprehensive guide to using Git and GitHub, covering a wide range of topics. It includes instructions on working directories, using submodules, writing good commit messages, deleting local repositories, and understanding Git workflows like Git Flow versus GitHub Flow. There are sections on packfiles, garbage collection, and the differences between concepts like HEAD, working tree, and index. Installation instructions for Git across various platforms Ubuntu, macOS, Windows, Raspberry Pi, Termux, etc. are provided, along with credential setup. The guide explains essential Git commands, their usage, and advanced topics like debugging, merging, rebasing, patch operations, hooks, subtree, filtering commit history, and handling merge conflicts. It also covers managing branches, syncing forks, searching errors, and differences between various Git operations e.g., push origin vs. push origin master, merging vs. rebasing. The text provides a comprehensive guide on using Git and GitHub. It covers creating repositories, adding code of conduct, forking and cloning projects, and adding various media files to a repository. The text explains how to push projects, handle authentication issues, solve common Git problems, and manage repositories. It discusses using different IDEs like VSCode, Android Studio, and PyCharm, for Git operations, including creating branches and pull requests. Additionally, it details deploying applications to platforms like Heroku and Firebase, publishing static websites on GitHub Pages, and collaborating on GitHub. Other topics include the use of Git with R and Eclipse, configuring OAuth apps, generating personal access tokens, and setting up GitLab repositories. The text covers various topics related to Git, GitHub, and other version control systems Key Pointers Git is a distributed version control system DVCS for source code management. Supports collaboration, continuous integration, and deployment. Suitable for both small and large projects. Developed by Linus Torvalds for Linux kernel development. Tracks changes, manages versions, and provides complete project history. GitHub is a hosting service for Git repositories. Tutorial covers Git and GitHub fundamentals and advanced concepts. Includes instructions on installation, repository creation, and Git Bash usage. Explains managing branches, resolving conflicts, and using platforms like Bitbucket and GitHub. Covers working directories, submodules, commit messages, and Git workflows. Details packfiles, garbage collection, and Git concepts HEAD, working tree, index. Provides Git installation instructions for various platforms. Explains essential Git commands and advanced topics debugging, merging, rebasing. Covers branch management, syncing forks, and differences between Git operations. Discusses using different IDEs for Git operations and deploying applications. Details using Git with R, Eclipse, and setting up GitLab repositories. Explains CI/CD processes and using GitHub Actions. Covers internal workings of Git and its decentralized model. Highlights differences between Git version control system and GitHub hosting platform.

2 trials left

Introduction:

Linked lists are data structures that store data elements in a linear manner. Each element of a linked list, known as a node, consists of two parts: data and a pointer that points to the next node in the list. A linked list can have one or more loops or cycles, where a node points to a previously visited node in the list. In this article, we will discuss how to find the length of a loop in a linked list using C programming language.

Algorithm:

To find the length of a loop in a linked list, we can use the Floyd's Cycle-Finding Algorithm, also known as the Tortoise and Hare algorithm. The algorithm involves two pointers, a slow pointer (tortoise) and a fast pointer (hare), that move through the list at different speeds. The slow pointer moves one step at a time, while the fast pointer moves two steps at a time. If the list has a loop, the two pointers will eventually meet at some point in the loop.

Once the two pointers meet, we can start a new pointer from the meeting point and move it along the loop until it returns to the meeting point. The number of nodes visited by this new pointer gives us the length of the loop in the linked list.

Implementation:

Let us now implement the algorithm in C programming language. We will define a linked list node structure that consists of an integer data value and a pointer to the next node in the list. We will also define a function called find_loop_length that takes a pointer to the head of the linked list as input and returns the length of the loop in the list. The implementation is as follows:

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

// Linked list node structure
struct Node {
    int data;
    struct Node* next;
};

// Function to find the length of the loop in the linked list
int find_loop_length(struct Node* head) {
    struct Node* tortoise = head;
    struct Node* hare = head;
    int loop_found = 0;
    int loop_length = 0;

    // Find the meeting point of the two pointers
    while (hare != NULL && hare->next != NULL) {
        tortoise = tortoise->next;
        hare = hare->next->next;
        if (tortoise == hare) {
            loop_found = 1;
            break;
        }
    }

    // If no loop is found, return 0
    if (loop_found == 0) {
        return 0;
    }

    // Find the length of the loop
    struct Node* ptr = tortoise;
    do {
        ptr = ptr->next;
        loop_length++;
    } while (ptr != tortoise);

    return loop_length;
}

// Function to create a new node in the linked list
struct Node* create_node(int data) {
    struct Node* node = (struct Node*)malloc(sizeof(struct Node));
    node->data = data;
    node->next = NULL;
    return node;
}

// Function to add a new node to the linked list
void add_node(struct Node** head, int data) {
    struct Node* node = create_node(data);
    node->next = *head;
    *head = node;
}

// Function to print the linked list
void print_list(struct Node* head) {
    struct Node* ptr = head;
    while (ptr != NULL) {
        printf("%d ", ptr->data);
        ptr = ptr->next;
    }
    printf("\n");
}

int main() {
    struct Node* head = NULL;

    // Create a linked list with a loop
    add_node(&head, 1);
    add_node(&head, 2);
    add_node(&head, 3);
    add_node(&head, 4);
    add_node(&head, 5);
    add_node(&head, 6);
    add_node(&head, 7);
    add_node(&head, 8);
    add_node(&head, 9);

struct Node* loop_start = create_node(10);
loop_start->next = head->next->next->next;
   add_node(&head, 11);
   add_node(&head, 12);
   add_node(&head, 13);
   add_node(&head, 14);
   add_node(&head, 15);
   add_node(&head, 16);
   add_node(&head, 17);
   add_node(&head, 18);
   add_node(&head, 19);
   add_node(&head, 20);

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

// Print the linked list
printf("Linked list: ");
print_list(head);

// Find the length of the loop in the linked list
int loop_length = find_loop_length(head);
printf("Length of the loop: %d\n", loop_length);

return 0;
}

In the main function, we create a linked list with 20 nodes and add a loop by making the next pointer of the last node point to the fourth node in the list. We then print the linked list and call the `find_loop_length` function to find the length of the loop in the list. Finally, we print the length of the loop.

Complexity:

The time complexity of the `find_loop_length` function is O(n), where n is the number of nodes in the linked list. The function first uses the Floyd's Cycle-Finding Algorithm to find the meeting point of the two pointers, which takes O(n) time in the worst case. It then uses a new pointer to traverse the loop, which takes O(k) time, where k is the length of the loop. Since k <= n, the overall time complexity is O(n).

The space complexity of the `find_loop_length` function is O(1), since it uses only constant amount of extra space for the pointers and loop variables.

Conclusion:

In this article, we have discussed how to find the length of a loop in a linked list using C programming language. We have implemented the Floyd's Cycle-Finding Algorithm to find the meeting point of two pointers in the list and then used a new pointer to traverse the loop and find its length. We have also discussed the time and space complexity of the algorithm.

You may also like this!