Copying a linked list and returning a pointer to the new list

ε祈祈猫儿з 提交于 2019-12-25 06:46:59

问题


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 ;
}


来源:https://stackoverflow.com/questions/22217990/copying-a-linked-list-and-returning-a-pointer-to-the-new-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!