c - Copying a linked list and returning a pointer to the new list -
my current struct is:
typedef char airportcode[4]; typedef struct node{ airportcode airport; struct node *next; }node;
my idea how function should start this:
node *copy(node *list) { int count = 0; while (list != null){ count++; list = list->next; } }
now know how long original list is, reason why stumped because have no idea how seperatly allocate memory each individual node have copy second list.
you allocate new node malloc:
node* newnode = malloc(sizeof(node));
then can change stuff inside new node with
newnode->airport = <blah blah blah> newnode->next = <other node, etc etc>
it might easier clone recursion rather loop, if use loop, unless lot of pointer manipulation , keep track of many nodes @ time (similar reversing linked list in place), use stack.
so this:
node* clonelist(node* head){ if (!head) return null;//done node* n = malloc(sizeof(node)); n->airport = head->airport; n->next = clonelist(head->next); return n; }
Comments
Post a Comment