【数据结构】双向链表

用循环双向链表实现了约瑟夫环问题。

/***************************************************
Copyright (c) 2015 Jingshuang Hu 
 
@filename:demo.c
@datetime:2015.09.18 
@author:HJS 
@e-mail:[email protected] 
@blog:http://blog.csdn.net/hujingshuang 
****************************************************/
#include 
#include 
/***************************************************/
typedef struct node
{
	int data;
	struct node *prior;
	struct node *next;

}Lnode, *LinkList;
/***************************************************/
LinkList List_Init(void);
void List_Joseph(LinkList h, int n, int m, int k);
int List_Show_Length(LinkList h);
void List_Show_All(LinkList h);
/***************************************************/
int main()
{
	LinkList p;

	p = List_Init();

	List_Show_Length(p);
	List_Show_All(p);
	List_Joseph(p, List_Show_Length(p), 5, 3);

	return 0;
}
/***************************************************/
LinkList List_Init(void)
{
	int i = 0, num = 0, value = 0;
	LinkList h = NULL;
	LinkList p, q;
	printf("双向链表长:");
	scanf("%d", &num);
	for (i = 0; i < num; i++)
	{
		scanf("%d", &value);
		p = (LinkList)malloc(sizeof(Lnode));
		p->data = value;
		p->next = p->prior = NULL;
		if (h == NULL)
		{
			h = p;
		}
		else
		{
			p->prior = q;
			q->next = p;
		}
		q = p;
	}
	h->prior = p;
	p->next = h;
	return h;
}
/***************************************************/
//元素:n	位置:m		间隔:k
void List_Joseph(LinkList h, int n, int m, int k)
{
	LinkList p = h, q;
	int i = 0, len = 0;

	for (i = 1; i < m; i++)
	{
		q = p;
		p = p->next;
	}
	while(len < n)
	{
		for (i = 0; i < k; i++)
		{
			q = p;
			p = p->next;
		}
		printf("%d ", p->data);
		p->next->prior = q;
		q->next = p->next;
		free(p);
		p = q->next;
		len++;
	}
	printf("\n");
}
/***************************************************/
int List_Show_Length(LinkList h)
{
	LinkList p = h;
	int length = 0;
	if (p->next == h || p->prior == h)
	{
		printf("表空!\n");
	}
	else
	{
		do
		{
			length++;
			p = p->next;
		}while(p != h);
		printf("表长:%d\n", length);
	}
	return length;
}
/***************************************************/
void List_Show_All(LinkList h)
{
	LinkList p = h;
	if (p->next == h)
	{
		printf("表空!\n");
	}
	else
	{
		do
		{
			printf("%d ", p->data);
			p = p->next;
		}while(p != h);
		printf("\n");
	}
}

你可能感兴趣的:(数据结构与算法分析,数据结构与算法分析)