//循环单链表删除KEY.c:是否在、在首、唯一一个、在尾
# include<stdio.h>
# include<stdlib.h>
# include<malloc.h>
# define array_size 50
typedef struct Node{
char data;
struct Node *next;
}Node,*Linklist;
int i,len,key,array[array_size];
Linklist head;
Linklist Createlist(int *array,int len)
{
Linklist temp,ptr;
head=(Node*)malloc(sizeof(Node));
if(head==NULL)//if(!head)
{printf("内存分配失败!");return NULL;}
head->data=array[0];
head->next=NULL;
temp=head;
for(i=0;i<len;i++)
{
ptr=(Node*)malloc(sizeof(Node));
if(ptr==NULL)//if(!ptr)
{printf("内存分配失败!");return NULL;}
ptr->data=array[i];
temp->next=ptr;
temp=temp->next;
}
ptr->next=head;
return head;
}
void Delete(Linklist head)
{
Linklist p,q,r;
p=(Node*)malloc(sizeof(Node));
if(p==NULL)//if(!head)
printf("内存分配失败!");
q=(Node*)malloc(sizeof(Node));
if(q==NULL)//if(!head)
printf("内存分配失败!");
r=(Node*)malloc(sizeof(Node));
if(r==NULL)//if(!head)
printf("内存分配失败!");
p=head;r=head;
while(p->data!=key)
{q=p;p=p->next;}//q是前驱
if(p==head)
{
if(head->next==NULL)
{head=NULL;free(head);printf("NULL\n");}//删除头节点后为空
else
{r=p->next;head=NULL;free(head);q=r->next;}//r是后继 删除头节点后不为空
}
if(p->next=head)//p是尾节点
{
p=p->next;free(p);r=p->next;q->next=r;
}
else
{
r=p->next;p->next=r->next;free(p);r=q->next;
}
}
void Print(Linklist head)
{
Linklist s;
s=(Node*)malloc(sizeof(Node));
if(s==NULL)//if(!head)
printf("内存分配失败!");
s=head;
while(s->next!=head)//打印节点的数值,哪里错了?求解释
{printf("%d,",s->data);s=s->next;}
}
int main()
{
printf("input len key:\n");
scanf("%d %d",&len,&key);
for(i=0;i<len;i++)
scanf("%d",&array[i]);
Createlist(array,len);
Delete(head);
Print(head);
return 0;
}
//@数据结构大神:查找并删除循环链表中的元素。85行的打印。为啥错了,求解释?