|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
这段代码我不知道错在哪里,望告知,十分感谢
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
struct Node
{
int data;
struct Node *next;
};
void printNode(struct Node *head,int n);
void printNode(struct Node *head,int n)//打印单链表数据
{ int i;
printf("现在开始打印%d个数:",n);
for(i=0;i<n;i++)
{
printf("%d\t",head->data);
head=head->next;
}
}
void createListhead(struct Node **head,int n);
void createListhead(struct Node **head,int n)//头插法创建单链表
{ int i;
struct Node *p;
*head=(struct Node*)malloc(sizeof(struct Node));
(*head)->next=NULL;
srand(time(0));
for(i=0;i<n;i++)
{p=(struct Node*)malloc(sizeof(struct Node));
p->data=rand()%100+1;
p->next=(*head)->next;
(*head)->next=p;
}
void main()
{ struct Node *head;
int n;
printf("请输入要输入多少个数:");
scanf("%d",&n);
createListhead(head,n);
printNode(head,n);
}
本帖最后由 最后的魁拔 于 2020-4-5 22:12 编辑
- #include<stdio.h>
- #include<stdlib.h>
- #include<time.h>
- struct Node
- {
- int data;
- struct Node *next;
- };
- void printNode(struct Node *head,int n);
- void printNode(struct Node *head,int n)//打印单链表数据
- { int i;
- printf("现在开始打印%d个数:",n);
- head = head->next; //你这个有头结点 先让head指向第一个真正的节点(不是头结点),
- for(i=0;i<n;i++)
- {
- printf("%d\t",head->data);
- head=head->next;
- }
- }
- void createListhead(struct Node **head,int n);
- void createListhead(struct Node **head,int n)//头插法创建单链表
- { int i;
- struct Node *p;
- *head=(struct Node*)malloc(sizeof(struct Node));
- (*head)->next=NULL;
- srand(time(0));
- for(i=0;i<n;i++)
- {p=(struct Node*)malloc(sizeof(struct Node));
- p->data=rand()%100+1;
- p->next=(*head)->next;
- (*head)->next=p;
- }
-
- } //你这儿好像少了一个大括号
- int main()
- { struct Node *head;
- int n;
- printf("请输入要输入多少个数:");
- scanf("%d",&n);
- createListhead(&head,n); //因为要在函数里面改变head,所以要传入地址
- printNode(head,n);
- system("pause");
- return 0;
- }
复制代码
|
|