我应该创建一个函数来显示第一个节点中的数据,然后使该节点成为列表中的最后一个节点。但我认为一种更简单的方法,就是在第一个节点之后使节点成为列表的头部,并在列表末尾插入一个新节点,该节点具有前一个节点的数据,我尝试使用不同的方法但是我这样做时会得到随机的问号和符号,我尝试了不同的方法,但我无法弄清楚问题是什么。
代码附在
下面 int places::showfirst()
{
node * current = head;
node * temp = current -> next;
node * temp2 = new node;
cout << "The first place you visited is \n\n\t\n " << 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;
}
任何建议都将不胜感激,谢谢你。
答案 0 :(得分:1)
不需要内存重新分配或取消分配IMO。您只需更改链接并将现有头节点转换为最后一个:
node * current = head;
node * temp = current -> next;
cout << "The first place you visited is \n\n\t\n " << current -> place << endl;
while(current->next)
{
current = current -> next;
}
current -> next = head;
head -> next = NULL;
head = temp;