C++ 链表程序打印最后一个数据项 n 次



我尝试自己创建链表程序。程序编译没有错误,但我没有得到正确的结果。
我已经在GCC和TURBO C++上尝试过。

#include<iostream>
#include<cstdio>
using namespace std;
struct node
{
char *name;
node *link;
};
int main()
{
int n, i;
node *start = NULL, *newnode, *temp;
char nam[10];
cout<<"Enter number of people:";
cin>>n;
for(i=0;i<n;i++)
{
cout<<"Enter name:";
fflush(stdin);
gets(nam);
if(start==NULL)
newnode = start = new node;
else
newnode = newnode->link = new node;
newnode->link = NULL;
newnode->name = nam;
}
cout<<"ntNames:";
temp = start;
while(temp!=NULL)
{
cout<<"n"<<temp->name;
temp = temp->link;
}
delete newnode;
delete start;
delete temp;
return 0;
}

输出为:
输出屏幕截图

Enter number of people:4
Enter name:qwerty
Enter name:uiop
Enter name:asdf
Enter name:zxcv
Names:
zxcv
zxcv
zxcv
zxcv
--------------------------------
Process exited after 15.85 seconds with return value 0

按任意键继续 . . .

它的作用是让所有节点指向同一个数组nam.这就是为什么所有节点的名称与上次输入的名称相同的原因。您必须为每个节点的name指针创建自己的内存(或在节点中将name设置为自动数组(,然后将nam复制到节点name


改变

newnode->name = nam;

newnode->name = new char [strlen(nam) + 1];
strcpy(newnode->name, nam);

另外,不要忘记delete[]分配的内存并阅读帖子下的评论,以免使用getsfflush


提示:

代替字符数组使用std::string.它的方式更易于使用且不易出错。

struct node
{
std::string name;
node *link;
};
std::string nam;
std::cin >> nam;
node->name = std::move(nam);

相关内容

最新更新