元素未添加到链表
Elements not being added to Linked List
我在元素未添加到我的链表中时遇到问题。我已经能够验证 char 字符串是否在 main() 中正确扫描并复制到临时节点,但这没有添加到链表中。
struct node{
char string[MAX_STRING_LENGTH];
node *next;
};
void insertAsFirstElement(node *head, node *last, char string[MAX_STRING_LENGTH])
{
//create temporary node
node *temp = new node;
printf("The temp's string before copy is %s.n", temp->string);
//this is the string copy from the user to the temp
strcpy(temp->string, string);
printf("The temp's string is %s.n", temp->string);
//set the next pointer to NULL (points to nothing)
temp->next = NULL;
//set first value in list to temp
head = temp;
//set last value to temp
last = temp;
}
//this is the string copy from temp to new
char *strcpy(char *temp, const char string);
这将声明strcpy
函数。你想称呼它。
strcpy(temp->string, string);
请不要混合搭配 C 和 C++。它们是非常不同的语言。如果您想在C++中执行此操作,那么它非常容易。
#include <string>
#include <list>
int main() {
std::list<std::string> strings;
char choice = menu();
while (choice != '4') {
switch (choice) {
case '1':
std::string input;
std::cout << "Please enter a string: ";
std::cin >> input;
strings.push_back(input);
break;
case '2':
strings.pop_front();
break;
case '3':
if (strings.size() == 0) {
std::cout << "The list is empty.n";
} else {
for (auto &s : strings) {
std::cout << s << "n";
}
}
break;
default:
std::cout << "System Exit";
return 0;
}
}
}
您发布的代码存在一些问题。
第一个是你的链表不包含字符串,它包含一个指针数组。
您应该省略char *string[MAX_STRING_LENGTH];
中的*
第二个是你对scanf
的呼唤。
scanf("%sn", &string[MAX_STRING_LENGTH]);
这会将程序用户的输入放入字符串后面的内存中。那不是你想要的。您希望用户的输入在字符串的开头进入内存,如下所示:
scanf("%sn", &string[0]);
或者写得更简单:
scanf("%sn", string);
最后,您不会将字符串复制到链表。您可以使用 strcpy
来做到这一点,如下所示:
strcpy(temp->string, string);
相关文章:
- 将数组的元素添加到链表中
- 如何在链表末尾添加?
- 需要左键作为赋值的左操作数?? 在链表中添加Add_End、删除和Delete_Front?
- 将两个数字添加为链表
- 如何向自身添加链表?
- 如何将节点添加到链表
- 在 C++ 中使用 temp 变量将节点添加到链表的末尾
- 为什么我在尝试添加两个链表时出现此错误?
- 使用链表添加多项式?援助
- 将元素添加到 Head 的双链表
- 如何在链表前面添加和返回节点
- 编写递归算法以从链表中删除元素.编写递归算法以将元素添加到链表中
- 在 c++ 程序中调试链表以添加两个数字: 有人可以解释为什么 l3=l3->next;导致错误?
- 双链表 - 添加/显示
- 通过链表添加多项式
- 使用链表添加两个数字
- 正在将链表添加到构造函数
- c++如何使用链表添加多项式
- 将结构体链表添加到数组中会产生错误
- 向链表添加新节点的新方法