实现动态链表的创建、删除、插入释放等功能
#include<stdio.h>
#include<malloc.h>
#define LEN sizeof(struct student)
int n;
struct student
{
char name[15];
int score;
struct student *next;
};
struct student *creat()
{
struct student*p2,*p1,*head;
n=0;
p1 = p2 = (struct student *)malloc(LEN);
scanf ("%s",&(p1->name));
scanf ("%d",&(p1->score));
head = NULL;
while(p1->score!=0)
{
if((++n)==1) head=p1;
else p2->next=p1;
p2=p1;
p1 = (struct student *) malloc (LEN);
scanf ("%s",&(p1->name));
scanf ("%d",&(p1->score));
}
p2->next = NULL;
return(head);
}
void print(struct student *head)
{
struct student *p;
p=head;
if(head!=NULL)
do
{
printf("%s %d\n",p->name,p->score);
p=p->next;
} while(p!=NULL);
}
void my_free(struct student *head)
{
struct student *p;
while(head != NULL)
{
p = head;
head = head->next;
free(p);
p = NULL;
}
}
void del(struct student *head,int n)
{
struct student *p_curr,*p_last;
int num = 1;
p_curr = head;
while(p_curr != NULL)
{
num++;
p_last = p_curr;
p_curr = p_curr->next;
if(num == n)
{
p_last->next = p_curr->next;
free(p_curr);
p_curr = NULL;
}
}
}
void insert(struct student *head, int n, char str_name[], int e)
{
struct student *p_last,*p_curr,*p_inst;
int num = 1;
p_inst = (struct student *)malloc(sizeof(struct student));
strcpy(p_inst->name, str_name);//字符数组的复制所用的函数
p_inst->score = e;
p_inst->next = NULL;
p_curr = head;
while(p_curr->next != NULL)
{
num++;
p_last = p_curr;
p_curr = p_curr->next;
if(num == n)
{
p_last->next = p_inst;
p_inst->next = p_curr;
break;//一定要有这个,执行完这个就不在执行下去了
}
}
}
void main()
{
struct student *head;
head=creat();
print(head);
del(head,2);
print(head);
insert(head, 2, "sun", 99);
print(head);
my_free(head);
}