码迷,mamicode.com
首页 > 编程语言 > 详细

《数据结构与算法分析——c语言描述》读后笔记 7

时间:2015-08-17 12:19:01      阅读:146      评论:0      收藏:0      [点我收藏+]

标签:linux c

给定两个已排序的表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
}


《数据结构与算法分析——c语言描述》读后笔记 7

标签:linux c

原文地址:http://yuzwei.blog.51cto.com/10126623/1685132

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!