我想创建一个从 1 到 1000 的数字链表并打印这些数字。
我使用函数 createList()
创建列表,使用 printList()
打印元素。
但是下面的代码崩溃了。
任何人都可以纠正。我是链表新手
#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node* link;
};
struct node* head;
void deleteNode()
{
}
void createList()
{
int i;
struct node* temp = (struct node*)malloc(sizeof(struct node));
head = temp;
struct node* temp1 = (struct node*)malloc(sizeof(struct node));
for(i=0;i<10;i++)
{
temp->data = i+1;
temp->link = temp1;
temp1->link = temp++;
temp1++;
}
}
void printList()
{
struct node* temp = (struct node*)malloc(sizeof(struct node));
temp = head;
while(temp != NULL)
{
printf("%d ", temp->data);
temp = temp->link;
}
}
int main()
{
head = NULL;
createList();
printList();
return 0;
}
最佳答案
void createList(){
int i, size = 10;
struct node* temp = malloc(sizeof(struct node));
head = temp;
for(i=0;i<size;i++){
temp->data = i+1;
temp->link = i < size - 1 ? malloc(sizeof(struct node)) : NULL;
temp = temp->link;
}
}
void createList(){
int i, size = 10;
struct node* temp = malloc(size*sizeof(struct node));
head = temp;
if(temp){
for(i=0;i<size;i++){
temp->data = i+1;
temp->link = temp + 1;
++temp;
}
temp[-1].link = NULL;
}
}
关于创建链表并打印元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21003205/