所以我在使用 C 中的链表时遇到了一些麻烦。总的来说,我了解了概念和算法,因为我已经在 Java 中学习了这些想法。但在 C 中似乎是另一回事,因为我们还考虑了内存分配。
无论如何,我这里有这段代码:
while (curr != NULL) {
printf("%s\n", (*curr).name);
curr = (*curr).next;
}
其中 curr
是一个 struct Student
并且 Student
的“属性”之一是 name
。所以假设我已经将我的节点添加到列表中。当我执行上面的命令时,我似乎得到了完全相同的名字。下面是我将节点添加到链表中的代码:
void insertNode(char *name, int idNum, char sex) {
struct Student *s;
s = malloc(sizeof(struct Student));
//not entirely sure if this is the right way to do it
if (s == NULL) {
printf("Memory allocation failed.");
return;
}
(*s).name = name;
(*s).idNum = idNum;
(*s).sex = sex;
(*s).next = head; //head is the start of the list
head = s; //inserting the node at the beginning of the list
curr = head; //place the current pointer at the start of list
}
基本上我对 int
和 char
似乎没有问题。如果我的列表中有 {"Alice", 1000, 'F'} -> {"Bob", 1001, 'M'} -> {"Charlie", 1002, 'M'}
,我注意到添加到列表中的姓氏 Alice
将被打印出来。所以打印输出将是:
Alice
Alice
Alice
我是不是做错了什么?有什么我想念的吗?我是 C 的初学者,仍在自学。非常感谢您的帮助和建议!
最佳答案
您需要跟踪头部指针。
这里是完整的工作代码:
#include <stdio.h>
#include <stdlib.h>
struct Student
{
char * name;
int idNum;
char sex;
struct Student * next;
};
struct Student * head=NULL;
struct Student *
insertNode (char *name, int idNum, char sex)
{
struct Student *s;
s = malloc (sizeof (struct Student));
if (s == NULL)
{
printf ("Memory allocation failed.");
return NULL;
}
(*s).name = name;
(*s).idNum = idNum;
(*s).sex = sex;
(*s).next = head; //head is the start of the list
head = s;
return head;
}
int
main ()
{
insertNode("Alice", 1, 'F');
insertNode("Peter", 2, 'M');
insertNode("Mike", 3, 'M');
while (head != NULL)
{
printf ("%s\n", (*head).name);
head = (*head).next;
}
}
输出:
Mike
Peter
Alice
但是,仍然可以在您的代码中进行大量改进。特别是,符号 (*s).name
在 C 中有一个简写形式,即 s->name
更简洁。您还可以避免使用全局 head 变量,而是传递它的指针,以便可以在两次调用之间维护其更改的值。
关于c - C 中的结构/链表/指针/字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49547455/