link.h
#ifndef _LINK_H
#define _LINK_H
struct student{
int age;
char name[10];
struct student *next;
};
typedef struct student info_t;
extern info_t *head;
#endif
link.c
#include "link.h"
#include <malloc.h>
#include <string.h>
#include <stdio.h>
info_t *init(char *name,int age)
{
info_t* p = (info_t*)malloc(sizeof(info_t));
if(p == NULL){
printf("malloc fail\n");
return NULL;
}
memset(p->name,'\0',sizeof(p->name));
strncpy(p->name,name,strlen(name));
p->age = age;
p->next = NULL;
return p;
}
void addTail(info_t *p)
{
info_t *head_p = NULL;
if(head == NULL){
head = p;
p->next = head;
return;
}
head_p = head;
do{
head_p = head_p->next;
}while(head_p->next != head);
head_p->next = p;
p->next = head;
}
void addFront(info_t* p)
{
info_t* head_p = NULL;
head_p = head;
if(head_p == NULL){
head = p;
p->next = head;
return;
}
head_p = head;
do{
head_p = head_p->next;
}while(head_p->next != head);
head_p->next = p;
p->next = head;
head = p;
}
void traverse()
{
info_t *head_p = head;
if(head_p == NULL)
printf("list is NULL\n");
do{
printf("name:%s,age:%d\n",head_p->name,head_p->age);
head_p = head_p->next;
}while(head_p!= head);
}
info_t *find (char *name,int age)
{
info_t *head_p = head;
if(head_p == NULL){
printf("list is NULL\n");
return NULL;
}
do{
if(strncmp(head_p->name,name,strlen(head_p->name)) == 0 && head_p->age == age)
return head_p;
head_p = head_p->next;
}while(head_p != head);
printf("lala\n");
return NULL;
}
info_t *del(char *name, int age)
{
info_t *p = NULL;
info_t *head_p = head;
if(head == NULL)
return NULL;
p = find(name,age);
if(p == NULL)
return NULL;
if(p == head){
do{
head_p = head_p->next;
}while(head_p->next != head);
head_p->next = head->next;
free(head);
head = head_p->next;
}else{
do{
head_p = head_p->next;
}while(head_p->next != p);
head_p->next = p->next;
free(p);
}
}
mian.c
#include <stdio.h>
#include "link.h"
info_t *head = NULL;
int main()
{
info_t * p = init("carl",10);
addTail(p);
p = init("nana",24);
addTail(p);
p = init("wkf",25);
addTail(p);
p = init("nihao",27);
addTail(p);
p = init("nimei",45);
addFront(p);
traverse();
p = del("nimei",45);
traverse();
}