循环链表内节点删除

/* 循环链表内节点删除 */
#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("找不到你所要的值。");
    }   
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值