Вопрос по c++ – Кодирование функции для копирования связанного списка в C ++

11

Мне нужно реализовать вспомогательную функцию с именем copyList, имеющую один параметр, указатель на ListNode. Эта функция должна возвращать указатель на первый узел копии исходного связанного списка. Итак, другими словами, мне нужно кодировать функцию на C ++, которая берет узел заголовка связанного списка и копирует весь этот связанный список, возвращая указатель на новый узел заголовка. Мне нужна помощь в реализации этой функции, и это то, что у меня есть сейчас.

Listnode *SortedList::copyList(Listnode *L) {

    Listnode *current = L;  //holds the current node

    Listnode *copy = new Listnode;
    copy->next = NULL;

    //traverses the list
    while (current != NULL) {
       *(copy->student) = *(current->student);
       *(copy->next) = *(current->next);

        copy = copy->next;
        current = current->next;
    }
    return copy;
}

Кроме того, это структура Listnode, с которой я работаю:

struct Listnode {    
  Student *student;
  Listnode *next;
};

Примечание: еще один фактор, с которым я сталкиваюсь в этой функции - это идея возврата указателя на локальную переменную.

Error: User Rate Limit Exceededstd::listError: User Rate Limit Exceeded Thomas Matthews
Error: User Rate Limit Exceeded Kevin Anderson
Error: User Rate Limit Exceeded André Caron
Error: User Rate Limit Exceeded Pat Murray
Error: User Rate Limit Exceeded Pat Murray

Ваш Ответ

7   ответов
0

copy

Listnode *startCopyNode = copy;

while (current != NULL) {
   *(copy->student) = *(current->student);
    copy->next = new Listnode;
    copy = copy->next;
 ,   current = current->next;
}

copy->next = NULL;
return startCopyNode;

delete

0

neweach

another factor I am running into with this function is the idea of returning a pointer to a local variable.

newdeleteoutside

0

2

excellent

# Detect empty list early.

if current == NULL:
    return NULL;

# Do first node as special case, maintain pointer to last element
# for appending, and start with second original node.

copy = new node()
last = copy

copy->payload = current->payload
current = current->next

# While more nodes to copy.

while current != NULL:
    # Create a new node, tracking last.

    last->next = new node()
    last = last->next

    # Transfer payload and advance pointer in original list.

    last->payload = current->payload
    current = current->next

# Need to terminate new list and return address of its first node

last->next = NULL
return copy

notheap-allocated

1






template <class T>
Node <T> * copy(Node <T> * rhs)
{
    Node <T> * current = new Node<T>();
    Node <T> * pHead = current;
    for (Node <T> * p = rhs; p; p = p->pNext)
    {
        Node <T> * prev = current;
        prev->data = p->data;
        if (p->pNext != NULL)
        {
            Node <T> * next = new Node<T>();
            prev->pNext = next;
            current = next;
        }
        else
        {
            prev->pNext = NULL;
        }
    }
    return pHead;
}

0

Error: User Rate Limit Exceededcopy->next = current->next is wrong. You should do

Create the first node copy here
copy->student = current->student;
copy->next = NULL;
while(current->next!=NULL)
{
    Create new node TEMP here
    copy->next = TEMP;
    TEMP->student = current->student;
    TEMP->next = NULL;
    copy = TEMP;
}
5

Student*?

struct Listnode {    
  Student *student; // a pointer?  shouldn't this be a `Student` object?
  Listnode *next;
};

Listnode *SortedList::copyList(Listnode *L) {

    Listnode *current = L;

    // Assume the list contains at least 1 student.
    Listnode *copy = new Listnode;
    copy->student = new Student(*current->student);
    copy->next = NULL;

    // Keep track of first element of the copy.
    Listnode *const head = copy;

    // 1st element already copied.
    current = current->next;

    while (current != NULL) {
       // Allocate the next node and advance `copy` to the element being copied.
       copy = copy->next = new Listnode;

       // Copy the node contents; don't share references to students.
       copy->student = new Student(*current->student);

       // No next element (yet).
       copy->next = NULL;

       // Advance 'current' to the next element
       current = current->next;
    }

    // Return pointer to first (not last) element.
    return head;
}

copy->student = current->student;

copy->student = new Student(*current->student);

Похожие вопросы