单向循环链表的头插 头删 尾插和尾删
//头结点插入
Linklist insere_element(Linklist head,datatype element)
{Linklist s=creat();s->data=element;if(NULL==head){head=s;}else{Linklist p=head;while(p->next!=head){p=p->next;}s->next=head;head=s;p->next=head;}return head;
}
/头删
Linklist head_del(Linklist head)
{if(NULL==head)return head;Linklist del=head;head=head->next;free(del);del=NULL;return head;
}
//尾插法
Linklist insert_rear(Linklist head,datatype element)
{//先创建一个结点Linklist s=creat();s->data=element;//判断是否为空if(head==NULL){head=s;}else//有多个节点的情况{Linklist p=head;//防止返回的时候出错,定义p为head,否则head改变后返回是错误的//找到最后一个结点while(p->next){p=p->next;}p->next=s;}return head;
}
//尾删
Linklist rear_del(Linklist head)
{Linklist del=NULL;if(NULL==head)return head;else if(head->next==NULL){free(head);head==NULL;}else{del=head;while(del->next->next){del=del->next;}free(del->next);del->next=NULL;}return head;
}
约瑟夫环
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
enum
{FALSE=-1,SUCCESS
};
typedef int datatype;
typedef struct Node
{datatype data;struct Node *next;
}*linklist;
linklist creat();
linklist insert_rear(linklist head,datatype element);
void output(linklist head);
linklist Joseph(linklist head,int n,int m);
linklist Joseph(linklist head,int n,int m)
{if(head==NULL)return head;linklist p=head;for(int i=0;i<n;i++){for(int j=0;j<m-2;j++){p=p->next;}linklist del=p->next;printf("%-5d",del->data);p->next=del->next;free(del);del=NULL;p=p->next;}return NULL;
}
int main(int argc, const char *argv[])
{//定义头指针linklist head=NULL;int n;datatype element;printf("please enter n:");scanf("%d",&n);//循环写入for(int i=0;i<n;i++){printf("please enter element:");scanf("%d",&element);head=insert_rear(head,element);}//遍历output(head);//约瑟夫环int m;printf("please enter m:");scanf("%d",&m);head=Joseph(head,n,m);return 0;
}