再论循环链表的插入和删除操作

 /* 再论循环链表的插入和删除操作 */
#include "stdio.h"
struct clist
{
 int data;
 struct clist *next;
};
typedef struct clist cnode;
typedef cnode *clink;
/*循环链表的输出*/
void printclist(clink head)
{
 clink ptr;
 head=head->next;/*指向链表的第一个结点*/
 ptr=head;
 do
 {
  printf("[%d]",ptr->data);
  ptr=ptr->next;
 }
 while(head!=ptr&&head->next!=head);
 printf("/n");
}
/*循环链表的结点插入*/
clink insertnode(clink head,clink ptr,int value)
{
 clink new_node;
 /*创建新结点分配结点内存*/
 new_node=(clink)malloc(sizeof(cnode));
 if(!new_node) return NULL;
 new_node->data=value;
 new_node->next=NULL;
 if(head==NULL)
 {
  new_node->next=new_node;
  return new_node;
 }
 if(ptr==NULL)
 {
  /*第一种情况:插在第一个结点前面*/
  new_node->next=head->next;
  head->next->next=new_node;
 }
 else
 {
  /*第二种情况:插在结点之后*/
  new_node->next=ptr->next;
  ptr->next=new_node;
 }
 if(head==ptr)
 {
  head=new_node;/*改变链表开始*/
 }
 return head;
}
/*循环链表的结点删除*/
clink deletenode(clink head,clink ptr)
{
 clink previous;
 if(head==NULL) return NULL;
 if(head->next==ptr)
 {   /*第一种情况:删除第一个结点*/
  head->next=ptr->next;
 }
 else
 {
  /*第二种情况:删除中间结点*/
  previous=head;
  if(head!=head->next)
  while(previous->next!=ptr)
  {
   previous=previous->next;
  }
  previous->next=ptr->next;
 }
 if(ptr==head)
 {
  head=previous;
 }
 free(ptr);
 return head;
}
/*主程序*/
void main()
{
    clink head=NULL;
    int list[6]={9,7,3,4,5,6};
    int i;
    head=insertnode(head,head,list[0]);
    printf("创建第一个结点:");
    printclist(head);
    /*第一中情况:插在第一结点前*/
    head=insertnode(head,NULL,list[1]);
    printf("插入第一结点之前:");
    printclist(head);
    for(i=2;i<6;i++)
    {
     /*第二种情况:插在结点之后*/
     head=insertnode(head,head->next,list[i]);
     printf("插入结点之后:");
     printclist(head);
    }
    /*第一种情况:删除第一个结点*/
    head=deletenode(head,head->next);
    printf("删除第一个结点:");
    printclist(head);
    /*删除最后一个结点*/
    printf("删除最后一个结点:");
    head=deletenode(head,head);
    printclist(head);
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值