0 Pluspunkte 0 Minuspunkte
Wie erstellt man eine Circular linked list wo alle Knoten im Kreis miteinander verbunden sind?

von  

1 Antwort

0 Pluspunkte 0 Minuspunkte

Eine Circular linked list ist eine "normale" Linked list wobei der letzte Knoten wieder an den ersten anschließt und somit eine Kette bildet.

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

struct Node {
    int data;
    struct Node* next;
};

int main() {

    struct Node* head = (struct Node*)malloc(sizeof(struct Node));
    head->next = NULL;

    struct Node* first = (struct Node*)malloc(sizeof(struct Node));
    first->data = 1;
    first->next = head; // Der nächste Knoten von "first" ist der Head-Knoten
    head->next = first; // Der Head-Knoten zeigt nun auf "first"

    struct Node* second = (struct Node*)malloc(sizeof(struct Node));
    second->data = 2;
    second->next = head; // Der nächste Knoten von "second" ist der Head-Knoten
    first->next = second; // Der nächste Knoten von "first" ist "second"

    struct Node* third = (struct Node*)malloc(sizeof(struct Node));
    third->data = 3;
    third->next = head; // Der nächste Knoten von "third" ist der Head-Knoten
    second->next = third; // Der nächste Knoten von "second" ist "third"

    struct Node* current = head->next;
    for (int i = 0; i < 15; i++) {    
        if(current != head)
            printf("%d ", current->data);           
        current = current->next;
    }

    current = head->next;
    while (current != head) {
        struct Node* temp = current;
        current = current->next;
        free(temp);
    }
    
    free(head);

    return 0;
}

von (716 Punkte)