circular_linked_list.c

linked lists Implementation

58 lines
1140 bytes
C
1// Circular Linked List
2#include <stdio.h>
3#include <stdlib.h>
4
5struct Node {
6    int data;
7    struct Node* next;
8};
9
10// Insert at end
11struct Node* insertAtEnd(struct Node* head, int data) {
12    struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
13    newNode->data = data;
14    
15    if (head == NULL) {
16        newNode->next = newNode;
17        return newNode;
18    }
19    
20    struct Node* temp = head;
21    while (temp->next != head) {
22        temp = temp->next;
23    }
24    
25    temp->next = newNode;
26    newNode->next = head;
27    return head;
28}
29
30// Display circular list
31void display(struct Node* head) {
32    if (head == NULL) {
33        printf("List is empty\n");
34        return;
35    }
36    
37    struct Node* temp = head;
38    printf("Circular List: ");
39    do {
40        printf("%d -> ", temp->data);
41        temp = temp->next;
42    } while (temp != head);
43    printf("(back to %d)\n", head->data);
44}
45
46int main() {
47    struct Node* head = NULL;
48    
49    head = insertAtEnd(head, 10);
50    head = insertAtEnd(head, 20);
51    head = insertAtEnd(head, 30);
52    head = insertAtEnd(head, 40);
53    
54    display(head);
55    
56    return 0;
57}
58