Copying a linked list and returning a pointer to t

2019-09-10 06:53发布

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.

2条回答
【Aperson】
2楼-- · 2019-09-10 07:30

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;
}
查看更多
爷、活的狠高调
3楼-- · 2019-09-10 07:31

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 ;
}
查看更多
登录 后发表回答