数据结构之链表的实例

来源:互联网 发布:mac tomcat端口被占用 编辑:程序博客网 时间:2024/06/07 16:43
/*约瑟夫死亡游戏*/#include <iostream>using namespace std;class Node{public:    int data;    Node *next;};class List{public:    List();    ~List();    void createList(int num);    void ListDelete(int num,int n,int other);    void ListTraverce();    Node *pList;};List::List(){    pList=new Node;    pList->next=pList;}List::~List(){    Node *currentNode=pList;    while(currentNode->next!=pList)    {        Node *temp=currentNode->next;        delete currentNode;        currentNode=temp;    }    delete pList;    pList=NULL;}void List::createList(int num){    if(num==0)    {        cout<<"输入有误";    }    else    {        pList->data=1;    }    Node *currentNode=pList;    for(int i=2;i<=num;i++)    {        Node *newNode=new Node;        newNode->data=i;        newNode->next=currentNode->next;        currentNode->next=newNode;        currentNode=newNode;    }}void List::ListDelete(int num,int n,int other){    Node *currentNode=pList;    Node *currentNodebefore=currentNode;    while(num>other)    {        for(int i=0;i<n-1;i++)        {            currentNodebefore=currentNode;            currentNode=currentNode->next;        }        cout<<currentNode->data<<endl;        num--;        Node *temp=new Node;        temp=currentNode->next;        currentNodebefore->next=temp;        currentNode=temp;    }}void List::ListTraverce(){    Node *currentNode=pList;    while(currentNode->next!=pList)    {        cout<<currentNode->data<<endl;        currentNode=currentNode->next;    }    cout<<currentNode->data<<endl;}int main(){    cout<<"请确定总人数";    int num;    cin>>num;    cout<<"请确认间隔的人数";    int n;    cin>>n;    cout<<"请确认剩余多少人";    int other;    cin>>other;    List *p=new List();    p->createList(num);   // p->ListTraverce();    p->ListDelete(num,n,other);    cout<<endl<<"剩余"<<endl;    p->ListTraverce();    delete p;    p=NULL;    return 0;}