#include #include struct node{ int data; struct node*next; }; struct node*head; struct node*insert(int x){ struct node*a=(struct node*)malloc(sizeof(struct node)); a->data=x; a->next=NULL; return a; }; void insertathead(int x){ struct node*b=insert(x); if(head==NULL) { head=b; return; } b->next=head; head=b; }; void print(){ struct node*c=head; while(c->next!=NULL); { printf("%d\t",c->data); c=c->next; } return; }; int main (void) { head=NULL; insertathead(1); insertathead(2); insertathead(3); print(); return 0; }
4条回答 默认 最新
benbenli 2021-05-23 13:06关注循环条件改为while (c != NULL),可以打呀。你看下面的代码和运行结果。
#include <stdio.h> #include <stdlib.h> struct node { int data; struct node * next; }; struct node * head; struct node * insert(int x) { //printf("Creating node for data %d\n", x); struct node * a = (struct node * ) malloc(sizeof(struct node)); a -> data = x; a -> next = NULL; return a; }; void insertathead(int x) { struct node * b = insert(x); if (head == NULL) { //printf("Head is NULL. %d is head.\n", x); head = b; return; } //printf("Head is not NULL. %d is inserted to head.\n", x); b -> next = head; head = b; }; void print() { struct node * c = head; while (c != NULL) { printf("%d\t", c -> data); c = c -> next; } return; }; int main(void) { head = NULL; insertathead(1); insertathead(2); insertathead(3); print(); return 0; } // Output 3 2 1本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报