题目:
代码:
Josephus.h
typedef int Status;
struct Lnode {
int data;
Lnode *next;
};
typedef Lnode Linklist ;
Status CreatJosephus_L ( Linklist &L , int n ) ;
Status OutputJosephus_L ( Linklist &L , int n ) ;
void MenuSelect ( Linklist &L ) ;
using namespace std ;
Josephus_app
#include<stdio.h>
#include<iostream>
#include"Josephus.h"
using namespace std ;
Status CreatJosephus_L ( Linklist &head , int n ) {
Lnode *L = &head ;
if ( n<=0 ) {
return 0 ;
}
int temp;
scanf( "%d", &temp ) ;
L->data = temp ;
n = n - 1 ;
while( n-- ) {
L->next = new(Lnode) ;
L = L->next ;
scanf( "%d", &temp ) ;
L->data = temp ;
}
L->next = &head ;
return 1;
}
Status CreatJosephus_L2 ( Linklist &head , int n ) {
Lnode *L = &head ;
if ( n<=0 ) {
return 0 ;
}
int temp = 1;
L->data = temp ;
n = n - 1 ;
while( n-- ) {
L->next = new(Lnode) ;
L = L->next ;
temp++;
L->data = temp ;
}
L->next = &head ;
return 1;
}
Status OutputJosephus_L ( Linklist &h , int n ) {
int m, k;
printf( "please input k and m :" ) ;
scanf( "%d%d", &k, &m ) ;
printf( "the seq with parameter( k=%d,m=%d ) is :\n", k, m ) ;
Lnode *p = &h ;
k-- ;
if ( k<0 || m<0 ) {
return 0 ;
}
while( k-- ) {
p = p->next ;
}
while( n>0 ) {
for( int i=2; i<m; i++ ) {
p = p->next ;
}
printf( "%d ", p->next->data ) ;
p->next = p->next->next ;
p = p->next ;
n--;
}
printf( "\n" ) ;
return 1;
}
void MenuSelect ( Linklist &L ) {
int op = -1 , st1 , st2 ;
int n ;
while( op != 0 ) {
printf( "please select op: " ) ;
scanf( "%d", &op ) ;
switch ( op ) {
case 0 :
printf( "over !\n" ) ;
break;
case 1 :
printf( "please input n:" ) ;
scanf( "%d", &n ) ;
printf( "please input seq :") ;
st1 = CreatJosephus_L ( L , n ) ;
if ( st1 == 0 ) {
printf( "error!\n" ) ;
}
break;
case 2 :
st2 = OutputJosephus_L( L , n ) ;
if ( st2 == 0 ) {
printf( "error\n" ) ;
}
else {
printf( "successful\n" ) ;
}
break;
default :
printf( "error!\n" ) ;
}
}
}
Josephus_Main
#include<stdio.h>
#include<iostream>
#include"Josephus.h"
using namespace std ;
int main() {
Linklist head ;
MenuSelect( head ) ;
return 0;
}
运行截图: