每天一练-c语言点点滴滴-约瑟夫环:

来源:互联网 发布:淘宝店铺全套装修 编辑:程序博客网 时间:2024/05/17 04:07

约瑟夫环:

当节点的指针域指向头结点的时候表示空!


 #include <stdio.h> #include <stdlib.h> typedef struct node {    int data;    struct node *next;}list,node;list *create_list(int a[], int n){   if ((NULL ==a) || (n <= 0)){   return NULL;}list *head=NULL, *p=NULL, *q=NULL;//构造第一个结点            head = (node *)malloc(sizeof(node));            head->data = a[0];            head->next = NULL;            q = head;            //构造其它节点int i=1;            for (i; i<n; i++)            {                //构造节点                p = (node *)malloc(sizeof(node));                p->data = a[i];                p->next = NULL;                //将节点加入链表                q->next = p;                q = q->next;            }            q->next = head;            return head;        }        void show_list(list *head)        {            if (NULL != head)            {                list *p=head;                printf("%d ", p->data);                while (p->next!= head)                {                       p=p->next;                    printf("%d ", p->data);                }                printf("\n");            }        }        void delete_node(list *head, int k, int m)        {            if ((NULL == head) || (k < 0))            {                return;            }            list *p=head, *q=NULL;            //算约瑟夫环大小            int len = 1;            while (p->next != head)            {                ++len;                p = p->next;            }            p = head;            //找报数的起点            while (k-- > 1)            {                p = p->next;            }            q = p;            while (len > 1)            {                //开始数mint  i;                for( i; i<m; i++)                {                    p = q;                    printf("%d\n", p->data);                    q = q->next;                     printf("%d\n", q->data);                }                p->next = q->next;//删除节点                 printf("delete node is: %d\n", q->data);                 q = p->next;                --len;            }            printf("last node is: %d\n", p->data);         }        int main()        {            int a[10] = {1,2,3,4,5,6,7,8,9};            list *head = NULL;            head = create_list(a,9);            show_list(head);            delete_node(head, 1, 2);            return 0;        }




Output:

12345678910
1 2 3 4 5 6 7 8 9 delete node is: 1delete node is: 2delete node is: 3delete node is: 4delete node is: 5delete node is: 6delete node is: 7delete node is: 8last node is: 1


原创粉丝点击