匿名用户
1级
2013-11-14 回答
#include
#include
typedef struct node
{
char data;
struct node* next;
}Lnode;
Lnode *head=NULL;
Lnode *tail=NULL;
void create()
{
head = (Lnode*)malloc(sizeof(Lnode));
tail = head;
if(head!=NULL)
{
printf("please input data: ");
scanf(" %c",&head->data);
head->next=NULL;
}
}
void delFirst(Lnode *pre ,Lnode *ptr,char x) //递归删除第一个 = x
{
if(ptr==NULL)
return;
if(pre==NULL && ptr->data == x)
{
head=ptr->next;
ptr->next = NULL;
free(ptr);
ptr=NULL;
return;
}
if(pre!=NULL && ptr->data == x)
{
pre->next = ptr->next;
ptr->next = NULL;
free(ptr);
ptr = NULL;
return;
}
pre = ptr;
ptr = ptr->next;
delFirst(pre,ptr,x);
}
void delAll() //递归删除所有
{
Lnode * tmp=NULL;
if(head==NULL)
return;
if(head->next!=NULL)
{
tmp = head->next;
free(head);
head=tmp;
delAll();
}
else
{
free(head);
head=NULL;
}
}
void insert()
{
if(tail == NULL)
return;
tail->next = (Lnode*)malloc(sizeof(Lnode));
if(tail->next != NULL)
{
printf("please input data: ");
scanf(" %c",&(tail->next->data));
tail=tail->next;
tail->next=NULL;
}
}
void print()
{
Lnode* tmp =head;
if(head==NULL)
printf("no data\n");
while(tmp!=NULL)
{
printf("%c ",tmp->data);
tmp=tmp->next;
}
}
void lfree() //非递归删除
{
Lnode* tmp=NULL;
while(head!=NULL)
{
tmp=head;
head=head->next;
free(tmp);
}
}
void main()
{
int i=0;
create();
for(i=0; i<5; i++)
{
insert();
}
delFirst(NULL,head,'1');
print(head);
delAll();
print(head);
}