约瑟夫问题循环链表做法

程序代码如下:

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

#define  LEN    41
#define  NUM     3

typedef struct LNode{
	int data;
	struct LNode *next;
}LNode; 


LNode* CreateLinklist(LNode *L)
{
	int i;
	LNode *p,*q;
	L=(LNode*)malloc(sizeof(LNode));
	assert(L!=NULL);
	p=L;
	for(i=0;i<LEN;i++)
	{
		q=(LNode*)malloc(sizeof(LNode));
		assert(q!=NULL);
		q->data=i+1;
		p->next=q;
		p=q;
	}
	p->next=L->next;
	free(L); 
	return p->next;                    //返回循环链表第一个节点	
}

void PrintLinklist(LNode *head)
{
	LNode *p,*q;
	p=head;
	while(p->next != p)
	{
		for(int i=1;i<NUM-1;i++)     //找到删除的前驱节点 
		{
			p=p->next;
		}
		printf("%d-->",p->next->data);
		q=p->next;                   //把要删除的结点赋给q 
		p->next=q->next;
		free(q);                    //释放掉删除结点 
		
		p=p->next;
	}
	printf("%d",p->data);
	
} 

/*约瑟夫问题*/
int main()
{
	LNode *L,*temp;
	temp=CreateLinklist(L);
    PrintLinklist(temp); 
	return 0;
}

运行截图:
在这里插入图片描述

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
循环链表是解决约瑟夫问题的一种常见方法。下面是一个使用Java循环链表解决约瑟夫问题的示例: ```java class Node { int data; Node next; public Node(int data) { this.data = data; } } class CircularLinkedList { private Node head; private Node tail; public void add(int data) { Node newNode = new Node(data); if (head == null) { head = newNode; tail = newNode; tail.next = head; } else { tail.next = newNode; tail = newNode; tail.next = head; } } public void remove(Node node) { if (head == null) { return; } if (head == node) { head = head.next; tail.next = head; } else { Node current = head; while (current.next != node) { current = current.next; } current.next = node.next; if (node == tail) { tail = current; tail.next = head; } } } public void josephus(int k) { Node current = head; while (current.next != current) { for (int i = 1; i < k; i++) { current = current.next; } System.out.print(current.data + " "); remove(current); current = current.next; } System.out.println(current.data); } } public class Main { public static void main(String[] args) { CircularLinkedList list = new CircularLinkedList(); int n = 7; // 总人数 int k = 3; // 报数为3的人出列 for (int i = 1; i <= n; i++) { list.add(i); } System.out.println("出列顺序:"); list.josephus(k); } } ``` 这段代码中,我们首先定义了一个`Node`类来表示循环链表的节点,然后定义了`CircularLinkedList`类来实现循环链表的操作。在`josephus`方法中,我们使用循环链表模拟约瑟夫问题的解决过程,每次找到第k个节点并移除,直到只剩下一个节点为止。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值