C++ 链表程序打印最后一个数据项 n 次
c++ linked list program printing last data item n times
我尝试自己创建链表程序。程序编译没有错误,但我没有得到正确的结果。
我已经在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[]
分配的内存并阅读帖子下的评论,以免使用gets
和fflush
。
提示:
代替字符数组使用std::string
.它的方式更易于使用且不易出错。
struct node
{
std::string name;
node *link;
};
std::string nam;
std::cin >> nam;
node->name = std::move(nam);
相关文章:
- lower_bound()返回最后一个元素
- 获取向量C++中第一个值和最后一个值的和
- 获取用C/C++打印的最后一个字符串
- 使用运算符 [] 引用 std::vector 上最后一个元素时出现问题<>
- 为什么这个程序返回最后一个单词而不是最长的单词?
- 为什么我的最后一个 ELSE 条件无法正确执行
- Lower_bound不适用于具有 3 个元素的向量的最后一个元素
- 查找数组中第一个最小值和最后一个最大值元素之间的算术平均值
- 仅显示链表的最后一个元素
- 测试迭代器是否位于列表中的最后一个
- push_back通过自行创建的对象获取最后一个元素的向量
- 使用 map.end() 访问 map 的最后一个元素
- 如何知道地图中的最后一个元素是否被删除?
- std::矢量保存 只推送最后一个元素
- 反转后不返回最后一个元素
- 如何删除矢量中的重复值,最后一个除外
- 如何在写入文件时擦除最后一个逗号
- 如何在新数组较小时创建新数组并将旧数组的最后一个元素复制到新数组中?
- 在 QListView 中显示最后一个元素
- C++ 链表程序打印最后一个数据项 n 次