其他分享
首页 > 其他分享> > 循环链表之魔法师发牌问题

循环链表之魔法师发牌问题

作者:互联网

Magician问题也是循环链表的经典问题,尽管其逻辑比较通俗易懂,但是用代码将其实现的方式更灵活,也更有味道。以下是源代码(本人新手,仅供自学和记录):

//魔术师发牌问题

#include<stdio.h>
#include<stdlib.h>

typedef struct node
{
	char data;
	struct node* next;
}node;

node* create(int n) {
	//初始化链表;
	node* p = NULL, * head;
	head = (node*)malloc(sizeof(node));
	p = head;
	node* s;
	for (int i = 1; i <= n; i++) {
		s = (node*)malloc(sizeof(node));
		s->data = 0;
		p->next = s;
		p = s;
	}
	s->next = head->next;
	free(head);
	return s->next;
}

node *  SN(node* s) {
	int i, n = 1;
	while (1) {
		for (i = 1; i < n; i++) {
			s = s->next;
			if (s->data != 0)
			{
				i--;
			}
		}
			s->data = n;
			n++;
			s = s->next;
			if (i == 14) {
				while (s->data!=1) {
					s = s->next;
				}
				return s;
		}
	}
}

int main(void) {
	int n = 14;
	node * s=SN(create(n));
	for (int i = 1; i <= 14; i++) {
		if (i == 14)
		{
			printf("黑桃%d  ", s->data);
		}
		else
		printf("黑桃%d -> ", s->data);
		s = s->next;
	}

}

代码实现:

 

标签:node,魔法师,head,int,next,链表,data,发牌
来源: https://blog.csdn.net/m0_57353463/article/details/119044200