链表
前言
学了这么久cpp居然不会用链表
被大二学长问得我无从下手力
代码
#include<iostream> using namespace std; typedef struct Node* linklist; //定义一个链表 typedef struct Node //用结构体设定链表参数 { int data; linklist next; }node; int n; linklist creat() { linklist head,p,q; head=new node; //在链表中新开一个节点 head->data=1; head->next=NULL; int x; cin>>n; for (int i=1;i<n;i++) { x=i+1; p=new node; p->data=x; p->next=NULL; //指向为空 if (head->next==NULL) head->next=p; else q->next=p; q=p; } q->next=head; return head; } int main () { linklist head; head=creat(); int m; cin>>m; int cnt=0,k=1; linklist p,q; p=head; q=head; while (cnt<n) //解决约瑟夫问题 { if (k==m) { cnt++; cout<<q->data<<" "; p->next=q->next; q=q->next; k=1; } else { k++; p=q; q=q->next; } } }
为何要逼自己长大,去闯不该闯的荒唐