Mam następujący kod (wszystko, czego dotyczy problem umieściłem w jednym pliku, żeby było łatwiej):
#include <stdio.h>
#include <stdlib.h>
typedef struct Tile
{
int value;
char *color;
} Tile;
typedef struct List
{
Tile *tile;
struct List *next;
} List;
Tile *tile_new(int value, char *color)
{
Tile *t = (Tile *) malloc(sizeof(Tile));
t->value = value;
t->color = color;
return t;
}
void tile_print(Tile *tile)
{
printf("[%d:%s]", tile->value, tile->color);
}
List *list_new(Tile *tile)
{
List *l = (List *) malloc(sizeof(List));
l->tile = tile;
l->next = NULL;
return l;
}
void list_print(List *list)
{
List *ptr = list;
while (ptr != NULL)
{
tile_print(ptr->tile);
ptr = ptr->next;
}
}
void list_append(Tile *tile, List *list)
{
List *ptr = list;
while (ptr->next != NULL)
ptr = ptr->next;
List *new_node = list_new(tile);
ptr->next = new_node;
}
Tile *list_remove_at(int n, List *list)
{
List *ptr = list;
if (n == 0)
{
Tile *t = list->tile;
*list = *(list->next);
free(ptr);
return t;
}
else
{
for (int i = 0; i < n - 1; i++)
ptr = ptr->next;
List *removed_node = ptr->next;
Tile *t = removed_node->tile;
ptr->next = removed_node->next;
//free(removed_node);
return t;
}
}
int main()
{
List *all_tiles;
for (int i = 0; i < 14; i++)
{
Tile *tile = tile_new(i, "red");
if (i == 0)
all_tiles = list_new(tile);
else
list_append(tile, all_tiles);
}
printf("all_tiles: ");
list_print(all_tiles);
printf("\n\ncreating a new list with a tile taken from the old one");
Tile *t = list_remove_at(0, all_tiles);
List *other_list = list_new(t);
printf("\n\nall_tiles: ");
list_print(all_tiles);
printf("\nother_list: ");
list_print(other_list);
return 0;
}
Zwraca mi to coś takiego:
all_tiles: [0:red][1:red][2:red][3:red][4:red][5:red][6:red][7:red][8:red][9:red][10:red][11:red][12:red][13:red]
creating a new list with a tile taken from the old one
all_tiles: [0:red]
other_list: [0:red]
Oczywiście oczekiwałem, aby all_tiles było listą od 1 do 13 po stworzeniu tej drugiej. Nie za bardzo rozumiem, co robię źle :(