在列表末尾插入具有第一个节点的数据的节点

Inserting a node at the end of the list with the data of the first node

本文关键字:节点 第一个 数据 列表 插入      更新时间:2023-10-16

我应该创建一个函数来显示第一个节点中的数据,然后使该节点成为列表中的最后一个节点。但我认为一个更简单的方法是,将第一个节点之后的节点作为列表的头,并在列表的末尾插入一个新节点,该节点包含前一个第一个节点的数据

代码附在下方

  int places::showfirst()
  {
        node * current = head;
        node * temp = current -> next;
        node * temp2 = new node;
        cout << "The first place you visited is nntn " << current -> place << endl;
        current->place = temporary;
        first = new char [strlen(temporary) +1];
        strcpy(first,temporary);
        while(current->next)
        {
              current = current -> next;
        }
        head = temp;
        current -> next = temp2;
        temp2 -> next = NULL;
        temp2->place = first;
        cout<<"THIS IS THE NEW LAST NODE " << temp2->place << endl;
        return 1;
  } 

如有任何建议,我们将不胜感激,提前谢谢。

不需要内存重新分配或取消分配IMO。您只需更改链接并将现有的头节点转换为最后一个:

node * current = head;
node * temp = current -> next;
cout << "The first place you visited is nntn " << current -> place << endl;
while(current->next)
{
    current = current -> next;
}
current -> next = head;
head -> next = NULL;
head = temp;