循环链表就自己写吧。结构体中就一个值加一个next指针,最后将next指向头。(我还是喜欢用数组做啊!)
for i=1~N
if i%M==0
cout<<...;
(应该没问题吧?)
两个栈,实现一个队列。
栈:stk1,stk2
进队列操作:就是对stk1进行压栈操作;
出队列操作:
先将stk1的东西依次出栈,
然后压栈到stk2中,
最后stk1为空,此时对stk2的栈顶做出栈操作(这个值就取出来,不压入到stk1中了),
最后将stk2的内容再出栈,压栈到stk1中。
诶,这个问题我刚好在算法书上看到过,就叫约瑟夫环问题。
//两个栈模拟队列
#include
using namespace std;
#define NULL 0
#define ok 1
#define yes 1
#define no 0
#define error 0
#define false 0
#define maxsize 100
struct stillstack//定义一个静态栈1,栈顶指针指向栈顶元素位置
{
int data[maxsize];
int top, bottom;
};
int initstack(stillstack &s)//对应静态栈1的初始化
{
s.top = s.bottom = -1;
return ok;
}
int push(stillstack &s, int e)//静态栈1入栈
{
if (s.top-s.bottom>=maxsize)
return error;
else
s.data[++s.top] = e;
return ok;
}
int pop(stillstack &s, int &e)//静态栈1出栈
{
if (s.top == s.bottom)
return error;
else
e = s.data[s.top--];
return ok;
}
int isempty(stillstack s)//两种栈都可以用bottom=top来判定栈空
{
if (s.top == s.bottom)
return yes;
else
return no;
}
int length1(stillstack s)//两种栈都可以用botto-top来求栈中元素个数
{
return s.top - s.bottom;
}
stillstack s1, s2;
int inqueue(int x)
{
int e;
while (!isempty(s2))
{
if (pop(s2, e))
push(s1, e);
}
if(push(s1, x))
return ok;
else
return error;
}
int outqueue(int &x)
{
int e;
while (!isempty(s1))
{
if (pop(s1, e))
push(s2, e);
}
if(pop(s2, x))
return ok;
else
return error;
}
int main()
{
int x=1,y=1,z;
while (1)
{
cout << "请输入要进行的操作0代表出队,1代表入队,999代表停止" << endl;
cin >> z;
if (z == 1)
{
cout << "请输入要入队的数据" ;
cin >> x;
if (inqueue(x))
continue;
else
cout << "队满";
}
if (z == 0)
{
if (outqueue(y))
cout << "出队的数据是" << y << endl;
else
cout << "已经出队完毕" << endl;
continue;
}
if (z = 999)
return ok;
}
}