代码如下:
#include
#include
typedef struct Node{
int data;
struct Node *next;
}Node;
Node *create(int n);
void insert(Node *head,int data,int n);
void display(Node *head);
void delete(Node *head,int n);
void my_free(Node *head);
int main()
{
Node *head;
int n;
printf("请输入元素个数:");
scanf("%d",&n);
printf("请输入数据:\n");
create(n);
display(head);
my_free(head);
return 0;
}
Node *create(int n)
{
Node *head,*pnew; int i;
head = (Node*)malloc(sizeof(Node));
head -> next = NULL;
for(i = 0;i < n; i++)
{
pnew = (Node*)malloc(sizeof(Node));
if (pnew == NULL)
printf("内存申请失败.");
else{
pnew -> next = NULL;
scanf("%d",&(pnew -> data));
pnew ->next = head -> next;
head -> next = pnew;
}
}return head;
}
void insert(Node *head,int data,int n)
{
Node *p,*pnew; int j = 0;
p = head;
while((p != NULL)&&(j < n)) {
p = p -> next;
j ++;
}
pnew -> next = p -> next;
p ->next = pnew;
pnew ->data = data;
}
void delete(Node *head,int n)
{
Node *p,*temp;int j = 0;
p = head;
while((j < n)&&(p != NULL) ){
p = p -> next;
j++;
}
temp = p -> next;
p -> next = temp -> next;
free(temp);
temp = NULL;
}
void my_free(Node *head)
{
Node *p,*q; p = head;
while(p != NULL)
{
q = p -> next;
free(p);
p = q;
}
}
void display(Node *head)
{
Node *p;
p = head -> next;
while(p != NULL)
{
printf("%d ",p -> data);
p = p -> next;
}
}运行结果:
请输入元素个数:3
请输入数据:
1
2
3
段错误