• 约瑟夫问题 双链表实现


    <span style="color:#cc33cc;">
    /*********************************
         author   : Grant Yuan
         algorithm; 双链表、
    	 time    。2014/10/3 20:38
     *********************************/   
    #include<iostream>
    #include <cstdio>
    #include<cstring>
    #include<cstdlib>
    #include<algorithm>
    using namespace std;
    
    typedef struct node
    {
    	int id;
    	struct node *front,*next;
    }Node,*PNode;
    int m,n;
    
    PNode Create_list()
    {
    	PNode head,p,q;
    	head=(Node *)malloc(sizeof(Node));
    	head->id=1;
    	p=(Node *)malloc(sizeof(Node));
    	p=head;
    	for(int i=2;i<=n;i++)
    	{
    		q=(Node *)malloc(sizeof(Node));
    		q->id=i;
    		q->front=p;
    		p->next=q;
    		p=q;
    	}
    	p->next=head;head->front=p;
    	return head;
    }
    
    void Delete_List(PNode p)
    {
    	while(p->next){
    		PNode q;
    		q=p->next;
    		free(p);
    		p=q;
    	}
    }
    PNode Get_Next_Node(PNode head,int k)
    {
    	PNode p=head;
    	for(int i=1;i<k;i++)
    	{
    	  p=p->next;
    	}
    	return p;
    }
    PNode Get_front_Node(PNode head,int k)
    {
    	PNode p=head;
    	for(int i=1;i<k;i++)
    	{
    		p=p->front;
    	}
    	return p;
    }
    
    void Delete_Node(PNode p)
    {
    	PNode q;
    	(p->front)->next=p->next;
    	(p->next)->front=p->front;
    }
    
    void Print_List(PNode head)
    {
    	PNode p=head;
    	printf("%d ",p->id);
    	p=p->next;
    	while(1){
    	   if(p==head) break;
    	   printf("%d ",p->id);
    	   p=p->next;
    	}
    	printf("
    ");
    }
    int main()
    {
        cin>>n>>m;
        PNode head,p,q;
        head=Create_list();
    	int ans;p=head;
         while(1){
    		p=Get_Next_Node(p,m);
    		q=p->next;ans=p->id;
    	    if(p->next==p) break;
    	    Delete_Node(p);
    	    p=q;
         }
         printf("%d
    ",ans);
        return 0;
    }
    </span>

  • 相关阅读:
    【LeetCode】141. Linked List Cycle
    linux配置java环境变量(详细)
    CUDA中的流与事件
    多语言协作与二进制交互【转】
    /usr/bin/ld: cannot find -lz
    机器学习经典书籍[转]
    Valgrind使用[转]
    Instructions函数对照表:02 xmmintrin.h与SSE指令集[转]
    Eclipse中10个最有用的快捷键组合
    C语言调试的几种方法
  • 原文地址:https://www.cnblogs.com/mengfanrong/p/5418512.html
Copyright © 2020-2023  润新知