Copying a linked list and returning a pointer to t

2019-09-10 06:48发布

问题:

My current struct is:

typedef char AirportCode[4];
typedef struct node{
  AirportCode airport;
  struct node *next;
}Node;

My idea for how the function should start is this:

Node *copy(Node *list) {
int count = 0;
  while (list != NULL){
   count++;
   list = list->next;
}
}

Now we know how long the original list is, but the reason why I am so stumped is because I have no idea how to seperatly allocate the memory for each individual node that we have to copy to the second list.

回答1:

You allocate a new node with malloc:

Node* newNode = malloc(sizeof(Node));

Then you can change stuff inside your new Node with

newNode->airport = <blah blah blah>
newNode->next = <other node, etc etc>

It might be easier to clone with recursion rather than loop, if you use a loop, unless you like to do a lot of pointer manipulation and keep track of many nodes at a time (similar to reversing a linked list in place), use a stack.

So it would be something like 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;
}


回答2:

I haven't tested it but this should do the job :

Node *copy(Node *list) {
  int count = 0;
  Node *previous = NULL ;
  Node *firstnode = NULL ;

  while (list != NULL){
   Node *newnode = malloc(sizeof(node)) ;

   if (firstnode == NULL)
     firstnode = newnode ;

   memcopy(newnode, list, sizeof(Node)) ;
   newnode->next = NULL ;

   if (previous != NULL)
     previous->next = newnode ;

   previous = newnode ;
   count++;
   list = list->next;
  }

  return firstnode ;
}