无法遍历 C 链表



任务是创建一个由对象组成的链表。用户输入main中每个单独Node的数据,然后将对象传递给push,这将创建列表。

问题出在printList函数中,其中从未满足break的条件。 出于某种原因,行head = head->next不执行任何操作,因为每次迭代的next地址保持不变。

typedef struct Node {
int a;
char asd[30];
struct Node *next;
}Node;
Node *head = NULL;
void push(Node**head, struct Node* object);
void printList(Node *head);
int main() {
struct Node {
int oA;
char oAsd[30];
struct Node *next;
};
struct Node *object = malloc(sizeof(struct Node));
int c = 0;
while (1) {
printf("This int will be stored in Node %d.n", ++c);
scanf("%d", &object->oA);
getchar();
if (!object->oA) {
break;
}
printf("This string will be stored in Node %d.n", c);
gets_s(object->oAsd, 30);
if (!(strcmp(object->oAsd, ""))) {
break;
}
push(&head, object);
}
printList(head);
return 0;
}
void push(Node ** head,  struct Node* object)
{
Node *tmp = malloc(sizeof(Node));
tmp = object;
tmp->next = (*head);
(*head) = tmp;
}

void printList(Node *head) {
if (head == NULL) {
puts("No list exists.");
exit(9);
}
while (1) {
printf("-------------------------------n");
printf("|Int: <%d> |||| String: <%s>.|n", head->a, head->asd);
printf("-------------------------------n");
if (head->next) {
printf("nn%pnn", head->next);
head = head->next;
}
else {
break;
}
}
}`

代码中有两个主要问题:

  • 您可以在main外部和内部定义struct Nodemain

  • 在这里tmp = object;您将一个指针的值复制到另一个指针,但您确实想将一个结构的值复制到另一个结构,即*tmp = *object;.

除此之外 - 不要将head作为全局变量。

所以代码应该更像:

typedef struct Node {
int a;
char asd[30];
struct Node *next;
}Node;
void push(Node**head, struct Node* object);
void printList(Node *head);
int main() {
Node *head = NULL;
struct Node *object = malloc(sizeof(struct Node));
int c = 0;
while (1) {
printf("This int will be stored in Node %d.n", ++c);
scanf("%d", &object->a);
getchar();
if (!object->a) {
break;
}
printf("This string will be stored in Node %d.n", c);
gets_s(object->asd, 30);
if (!(strcmp(object->asd, ""))) {
break;
}
push(&head, object);
}
printList(head);
return 0;
}
void push(Node ** head,  struct Node* object)
{
Node *tmp = malloc(sizeof(Node));
*tmp = *object;                    // Copy the struct
tmp->next = (*head);
(*head) = tmp;
}

void printList(Node *head) {
if (head == NULL) {
puts("No list exists.");
exit(9);
}
while (1) {
printf("-------------------------------n");
printf("|Int: <%d> |||| String: <%s>.|n", head->a, head->asd);
printf("-------------------------------n");
if (head->next) {
printf("nn%pnn", head->next);
head = head->next;
}
else {
break;
}
}
}

相关内容

  • 没有找到相关文章

最新更新