Verdoppelung von Knoten mit Vielfachen von 5 in einer verketteten Liste
Ob eine einzige verkettete Liste, in der die Knoten wie folgt definiert sind:
node (
int data;
node * next;
);
Führen Sie eine Verdoppelung aller Knoten durch, deren Daten Vielfache von 5 sind.
Beispiel
Wenn die ursprüngliche Liste
| -> | 2 | -> | 5 | -> | 3 | -> | 6 | -> | 10 | -> | 1 | -> | 5 | -> | X |
ist, wäre die endgültige Liste
| -> | 5 | -> | 10 | -> | 5 | -> | 2 | -> | 5 | -> | 3 | -> | 6 | -> | 10 | -> | 1 | -> | 5 | -> | X |
Implementierung in C
#include und #define N_NODOS 15
Definition der Struktur der Liste
struct node {
int data;
struct node * next;
};
typedef struct node tNode;
typedef struct node * TList;
Initialisierung der Liste
/* Füllt die Liste mit N_NODOS Knoten */
void inicializa_lista(TList * list) {
int i;
tNode * pNodo = NULL;
tNode * aux = NULL;
for (i = 0; i < N_NODOS; i++) {
pNodo = (tNode *) malloc(sizeof(tNode));
pNodo->data = i;
pNodo->next = NULL;
if (*list == NULL) {
/* Die Liste ist leer */
*list = pNodo;
} else {
/* Die Liste ist nicht leer: Wir suchen den letzten Knoten und fügen den neuen Knoten danach ein */
aux = *list;
while (aux->next != NULL)
aux = aux->next;
aux->next = pNodo;
}
}
}
Ausgabe der Liste
/* Gibt die Liste auf dem Bildschirm aus */
void imprime_lista(TList list) {
tNode * aux = NULL;
printf("\n| -> ");
aux = list;
while (aux != NULL) {
printf("| %d | -> ", aux->data);
aux = aux->next;
}
printf("| X |\n");
}
Verdoppelung der Knoten
/* Lösung des Problems */
void duplica_nodos(TList * list) {
TList lista_aux = NULL;
tNode * aux = NULL;
tNode * aux2 = NULL;
tNode * copy = NULL;
aux = *list;
while (aux != NULL) {
if (aux->data % 5 == 0) {
copy = (tNode *) malloc(sizeof(tNode));
if (copy != NULL) {
copy->data = aux->data;
copy->next = NULL;
if (lista_aux == NULL) {
/* Wenn die Hilfsliste leer ist */
lista_aux = copy;
} else {
/* Wenn die Hilfsliste nicht leer ist */
aux2 = lista_aux;
while (aux2->next != NULL)
aux2 = aux2->next;
aux2->next = copy;
}
}
}
aux = aux->next;
}
/* Schließlich wird die Hilfsliste vor die ursprüngliche Liste gehängt */
if (lista_aux != NULL) {
aux = lista_aux;
while (aux->next != NULL)
aux = aux->next;
aux->next = *list;
*list = lista_aux;
}
}
Hauptprogramm
int main() {
TList list = NULL;
inicializa_lista(&list);
imprime_lista(list);
duplica_nodos(&list);
imprime_lista(list);
getch();
return 0;
}