C-数据结构-单向循环链表

发布于:2024-05-24 ⋅ 阅读:(153) ⋅ 点赞:(0)

单向无头结点一定要注意传参 一般是二维指针问题 非常容易出错
约瑟夫算法
jose.c

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

struct node_st
{
	int data;
	struct node_st *next;

};
struct node_st *jose_create(int n)
{
	struct node_st *me;
	struct node_st *newnode,*cur;
	int i = 1;
	
	me = malloc(sizeof(*me));
	if(me == NULL)
		return NULL;
	me->data = i;
	me->next = me; 
	i++;
	
	cur = me;
	for(;i<= n;i++)
	{	
		newnode = malloc(sizeof(*newnode));
		if(newnode = NULL)
			return NULL;
		newnode->data = i;
		newnode->data = me;	

		cur->next = newnode;
		cur = newnode;
	}
	
	return me;
}
void jose_show(struct node_st *me)
{
	struct node_st *list;
	for(list = me;list->next != me ;list=list->next)
	{
		
		printf("%d ",list->data);
		//sleep(1);
		//fflush(NULL);
	}
	printf("%d\n",list->data);

}
void jose_kill(struct node_st **me,int n)
{
	struct node_st *cur = *me,*node;
	int i=1;
	while(cur != cur->next)
	{
		while(i < n)
		{
			node = cur;
			cur = cur->next;
			i++;
		}
		printf(""%d ",cur->data);
		node->next = cur->next;
		free(cur);
		
		cur = node->next;
		i = 1;
	}
	*me = cur;
	printf("\n");
}


int main()
{
	struct node_st *list;
	int n = 3;
	list = jose_create(JOSE_NR);
	if(list == NULL)
		exit(1);
		
	jose_show(list);
	jose_kill(&list,n);
	jose_show(list);	
	
	exit(0);
}

网站公告

今日签到

点亮在社区的每一天
去签到