1018击鼓传花1081猴子报数(循环链表实现)

在这里插入图片描述
输入:5
输出:4

#include<bits/stdc++.h>
using namespace std;
typedef struct node{
	int data;
	node * next;
}node;
int main()
{
	int n;
	cin>>n;
	//建立循环链表 
	node *head=new node;
	head->data=n;
	head->next=NULL;
	node *tail=head;
	for(int i=n-1;i>=1;--i)
	{
		node *p=new node;
		p->data=i;
		p->next=head;
		head=p;		
	}
	tail->next=head;//首尾相连 
	
	
	//删除 
	while(head->next!=head)
	{
		node *q=head->next;
		node *p=head->next->next;//要删除的节点 
		q->next=p->next; 
		head=p->next; 
		delete p;
	}
	cout<<head->data<<endl;
	return 0;
}

在这里插入图片描述
输入

10
2 5 
5
2 3 
0
0 0

输出

6,1,7,3,10,9,2,5,8,4
4,2,1,3,5

代码:

#include<bits/stdc++.h>
using namespace std;
typedef struct node{
	int data;
	node * next;
}node;
int main()
{
	int n,s,m;
	while(cin>>n>>s>>m)
	{
		if(n+s+m==0) break;
		node * head=new node;
		head->data=n;
		head->next=NULL;
		node *tail=head;
		for(int i=n-1;i>=1;--i)
		{
			node *p=new node;
			p->data=i;
			p->next=head;
			head=p;
		}
		tail->next=head;			
		
		s=s-1;	
		while(s--)
		{
			head=head->next;
		}		
		
		if(m==1) 
		{
			while(head!=tail)
			{
				cout<<head->data<<",";
				head=head->next;
			}
			cout<<head->data<<endl;
		}
		else
		{				
			while(head->next!=head)
			{
				node *pre=head,*after;				
								
				int t=m-2; 			
				while(t--)//找要删除节点的前一个节点 
				{
					pre=pre->next;
				}
				after=pre->next;//要删除的节点 
				pre->next=after->next;
				head=after->next;
				cout<<after->data<<",";
				delete after;		
				
			}
			cout<<head->data<<endl;
		}
	}
	return 0;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值