MyLinkList.h
#include
#include
#define NEW (struct node *)malloc(sizeof(struct node))
struct node
{
char name[20];
char tel[9];
struct node *next;
};
/* 创建 linked list */
struct node *create()
{
static struct node *h;
struct node *p,*q;
char name[20];
h = NULL;
printf("name : ");
gets(name);
while(0 != strlen(name))
{
p = NEW;
if(NULL == p)
{
printf("allocation failure \n");
exit(0);
}
strcpy(p->name,name);
printf("tel : ");
gets(p->tel);
p->next = NULL;
if(NULL == h)
h = p;
else
q->next = p;
q = p;
printf("name: ");
gets(name);
}
return h;
}
/* 遍历linked list */
void printlist(struct node *head)
{
struct node *p;
p = head;
while(NULL != p)
{
printf("%s\t%s\n",p->name,p->tel);
p = p->next;
}
}
/* 删除节点 */
struct node *delnode(struct node *head, char *x)
{
struct node *p,*q;
static struct node *h;
if(NULL == head)
{
printf("this is a empty linked list");
return head;
}
p = head;
while(0 != strcmp(x,p->name) && NULL != p->next)
{
q = p;
p = p->next;
}
if(0 == strcmp(x,p->name))
{
if( p == head)
head = p->next;
else
q->next = p->next;
free(p);
}
else
printf("can't find your node");
h = head;
return h;
}
main.c
#include
#include "MyLinkList.h"
int main(void)
{
struct node *head;
head = create();
printf("-----------遍历测试-----------------\n");
printlist(head);
printf("---------删除测试-------------\n");
char *delchar[20];
gets(delchar);
delnode(head,delchar);
printlist(head);
printf("-------------------------------\n");
printf("-------------------------------\n");
printf("-------------------------------\n");
}