利用循环链表对约萨夫问题进行求解

#include <iostream>
using namespace std;

template<class T>
struct node
{ T d;
 node *next;
};


//定义循环链表类
template<class T>
class linked_clist
{private:
    node<T> *head;//循环链表表头指针
 public:
    linked_clist();
    void prt_linked_clist( );//打印
    void ins_linked_clist(T ,T );//插入
    int del_linked_clist(T );//删chu
    void solve(node<T>*x,int n,int m);
    void ins_linked_clist(T);
};

template<class T>
linked_clist<T>::linked_clist( )
{
     node<T> *p;
      p=new node<T> ;
      p->d=1;
      p->next=p;
      head=p;
      return ;
}

template<class T>
void linked_clist<T>::prt_linked_clist()
{  node<T> *p;
   p=head->next;
  if (p == head)
 {     cout<<"空循环链表!"<<endl;
        return;
 }
 do{cout<<p->d<<"   " ;
        p=p->next;
      }while(p!=head);
    return;
}

 template<class T>
void linked_clist<T>::ins_linked_clist(T x,T b)
{
        node<T> * p ,*q;
        p=new node<T>;
        p->d = b;
        q=head;
        while((q->next!=head)&&(((q->next)->d)!=x))
            q=q->next;
        p->next=q->next;
        q->next=p;
        return;
}
 template<class T>
void linked_clist<T>::ins_linked_clist(T b)
 {
        node<T>* p = new node<T>;
        node<T>* q = head;
        p->d =b;
        if (head) {
            while (1) {
                q = q->next;
                if (q->next == head)
                    break;
            }
            p->next = q->next;
            q->next = p;
        } else {
            head = p;
            head->next = head;
        }
 }

//shanchu
template<class T>
int linked_clist<T>::del_linked_clist(T x)
{  node<T>*p, *q;
    q = head;
    while((q->next!=head)&&(((q->next)->d)!=x))
            q=q->next;
    if(q->next==head) return(0);
   p=q->next;
   q->next=p->next;
   delete p;
   return (1);
}

template<class T>
void linked_clist<T>::solve(node<T>*x,int n,int m)
{
    x=head;
    int i,j;
    node<T>*p;
    node<T>*q;
    for(i=1;i<=n;i++)
    {
        p=x;
        j=1;
        for(j=1;j<m-1;j++)
        {
            p=p->next;
        }
        q=p->next;
        cout<<q->d+1<<"  ";
        p->next=q->next;
        x=p->next;
    }
    cout<<p->d+1<<endl;
}

int main( )
{
    int n=41;

    node<int> *p;
    linked_clist<int> s ;
    for(int i=1;i<n;i++)
    {
        s.ins_linked_clist(i);
    }
    cout<<"死亡顺序: "<<endl;
    s.solve(p, n-1,3);
    return 0;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值