2
#include <stdio.h>
#include <stdlib.h>

定义结构

typedef struct node{
char name[20];
struct node *next;
}Node;

Node *head = NULL;

void insert ();

int main (){

Node *student1, *student2;
Node *walker;
int i;

head = (Node*)malloc(sizeof(Node));

for (i=0; i<3; i++) insert();

walker = head;

while(walker != NULL){
    printf ("%s\n", walker->name);
    walker = walker->next;  
}
return 0;

这个循环工作正常,但在程序崩溃之前最后添加了一些垃圾

}

在开头插入新节点

void insert(){
Node* nn;

nn = (Node*)malloc(sizeof(Node));

printf ("Name: ");
scanf ("%s", nn->name);

nn->next = head;
head = nn;

return;
}
4

1 回答 1

4

由于head->next未初始化,因此链表末尾没有空终止符。这会导致未定义的行为。

/* In main() */

head = malloc(sizeof(Node));
head->next = NULL;
于 2013-03-27T12:06:52.117 回答