给定两个已排序的表L1,L2,只使用基本的表操作编写计算L1∩L2的过程。
注:表都有表头。
struct Node;
typedef struct Node *PtrToNode;
typedef PtrToNode List;
typedef PtrToNode Position;
struct Node
{
ElementType Element;
Position Next;
}
程序:
List linkunion(List L1,List L2)
{
List L=malloc(sizeof(struct Node));
if(L==NULL)
{
printf("Linklist L is NULL !\n");
return L;
}
Position p=L1->Next,q=L2->Next,r=L;
while(p!=NULL && q!=NULL)
{
if(p->Element < q->Element)
{
p=p->Next;
}
else if(p->Element > q->Element)
{
q=q->Next;
}
else
{
Position tmp=malloc(sizeof(struct Node));
if(tmp==NULL)
{
printf("the node tmp is NULL !\n");
return 0;
}
tmp->Element=p->Element;
tmp->Next=NULL;
r->Next=tmp;
r=r->Next;
p=p->Next;
q=q->Next;
}
}
return L;
}Josephus问题是下面的游戏:N个人从1到N编号,围坐成一个圆圈,从1号开始传递一个热土豆。经过M次传递后拿着热土豆的人被清除离座,围坐的圆圈缩进,由坐在被清除的人后面的人拿起热土豆继续进行游戏。最后剩下的人取胜。因此,如果M=0和N=5,则依次被清除后,5号获胜。如果M=1和N=5,那么被清除的人的顺序是2,4,1,5.
程序:
int josephus(int M, int N)
{
int i=N,j=0,tmp,n[N]={0};
while(i!=1)
{
//选出被清除的人,编号为j+1,数组下标为j
for(tmp=0;tmp<M;)
{
if(n[j]==0)
tmp++;
j=(j+1)%N;
}
//清除编号为j+1的人,总人数i减 1
n[j]=1;
i--;
//选出下一个开始传递热土豆的人
while(n[(j+1)%N]!=0)
j++;
j=(j+1)%N;
}
return j+1; //j+1 is the number of the last person
}原文:http://yuzwei.blog.51cto.com/10126623/1685132