/* 循环链表内节点删除 */
#include "stdio.h"
struct clist
{
int data;
struct clist *next;
};
typedef struct clist node;
typedef node *clink;
/*使用数组值创建循环链表*/
clink createclist(int *array,int len)
{
clink head,before,new_node;
int i;
head=(clink)malloc(sizeof(node));
if(!head) return NULL;
head->data=array[0];
head->next=NULL;
before=head;
for(i=1;i<len;i++)
{
new_node=(clink)malloc(sizeof(node));
if(!new_node) return NULL;
new_node->data=array[i];
new_node->next=NULL;
before->next=new_node;
before=before->next;
}
new_node->next=head;
return head;
}
/*循环链表的遍历*/
clink findcode(clink head,int value)
{
clink ptr;
ptr=head;
do
{
if(ptr->data==value)
return ptr;
ptr=ptr->next;
}
while(head!=ptr&&head!=head->next);
return NULL;
}
/*循环链表输出*/
void printclist(clink head)
{
clink ptr;
ptr=head;
do
{
printf("[%d]",ptr->data);
ptr=ptr->next;
}
while(head!=ptr&&head!=head->next);
printf("/n");
}
/*循环链表的结点删除*/
clink deletenode(clink head,clink ptr)
{
clink previous;
if(head==NULL) return NULL;
previous=head;
if(head->next!=head)
while(previous->next!=ptr)/*查找ptr的前结点*/
previous=previous->next;
if(head==ptr)
{
/*第一种情况:删除第一个结点*/
head=head->next;
previous->next=ptr->next;
}
else
{
/*第二中情况:删除中间结点*/
previous->next=ptr->next;
}
free(ptr);
return head;
}
/*主函数*/
void main()
{
clink head;
clink find;
int list[6]={9,7,3,4,5,6};
int value;
head=createclist(list,6);
if(!head)
{
printf("内存分配失败!/n");
exit(1);
}
printf("链表内容是:");
printclist(head);
while(1)
{
printf("请输入查询值==》:");
scanf("%d",&value);
if(value==-1)
{
printclist(head);
exit(1);
}
find=findcode(head,value);
if(find!=NULL)
{
printf("删除的值:%d/n",find->data);
head=deletenode(head,find);
printclist(head);
}
else
printf("找不到你所要的值。");
}
}