数据结构之约瑟夫问题(循环链表)(C++版)
#include <iostream>
#include <stdlib.h>
using namespace std;
typedef char ElemType;
typedef struct LNode{
ElemType data; //数据域
struct LNode *next; //指针域
}LNode, *SLink;
void InitList(SLink &L){
SLink p, r;
int n, j;
cout << "请输入单链表元素个数:";
cin >> n;
//创建一个带头节点的空链表,L为指向头节点的指针(头指针)
L = (SLink) malloc (sizeof(LNode));
r = L;
if(!L) exit(0); //存储空间分配失败
cout << "请输入单链表的元素:";
for(j = 0; j < n; j++)
{
p = (SLink) malloc (sizeof(LNode)); //生成新节点
cin >> p->data; //输入元素值
r->next = p; r = p; //插入到表头
}
r->next = NULL;
}//InitList
int main()
{
SLink B, D, L, p, q, rb, rd, rl;
InitList(L);
B = new LNode; B->next = B; //创建空循环链表存放字母
D = new LNode; D->next = D; //创建空循环链表存放数字
rb = B; rd = D; rl = L;
p = L; q = p->next;
while(q)
{
if(('A' <= q->data) && (q->data <= 'Z') || ('a' <= q->data) && (q->data <= 'z'))
{
p->next = q->next; B->next = q; q->next = B; B = q; //尾插法
}
else if(('0' <= q->data) && (q->data <= '9'))
{
p->next = q->next; D->next = q; q->next = D; D = q;
}
else p = q;
q = p->next;
}
p->next = L; //将链表L构造为循环链表,存储其他字符
while(rb->next != B)
{
rb = rb->next;
cout << rb->data << ' ';
}
cout << B->data << endl;
while(rd->next != D)
{
rd = rd->next;
cout << rd->data << ' ';
}
cout << D->data <<endl;
while(rl->next != L)
{
rl = rl->next;
cout << rl->data << ' ';
}
cout << endl;
return 0;
}