约瑟夫环(无头结点的循环链表)

约瑟夫环(无头结点的循环链表)


通过这个程序熟悉了如何建立循环链表,以及指针的许多问题。这个题采用了无头指针的循环链表。
1.明白了无头指针的循环链表和普通的循环链表的区别。
2.关于链表长度的求法。
3.创建链表一般返回的是尾指针,尾指针可以方便的找到头指针。以及每次用指针时,记得保存指针。
4.

typedef struct Node {
	int id;
	int password;
	struct Node *next;
}Nodetype;

在结构体定义时不能用stuct Nodetype *next 是因为在程序执行到这条语句的时候typedef语句还没有定义好Nodetype。
5.YueSeFu函数中使用了两个指针(快慢指针)

	Nodetype *LA = r;
	Nodetype *LB = r->next;

使用这两个指针很方便找到LB的前驱从而实现删除结点的操作,而不用每次都循环遍历去删除当前。降低了时间复杂度。O(n) -> O(1)。
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
下面为代码

#include 
#include
typedef struct Node {
	int id;
	int password;
	struct Node *next;
}Nodetype;

Nodetype *Creatlist(){
	Nodetype *L;
	Nodetype *pNew,*r;
	int ID = 1;
	int m;
	int MAX;
	int count = 0;
	L = (Nodetype*)malloc(sizeof(Nodetype));
	L->next = NULL;
	r= L;
	printf("一共有多少个人:"); 
	scanf("%d",&MAX); 
	while (count < MAX){
		pNew = (Nodetype*)malloc(sizeof(Nodetype));
		printf("please enter the %d th password:\n",ID);
		pNew->id = ID++;
		scanf("%d",&m);
		pNew->password = m;
		r->next = pNew;
		r = pNew;
		count = count + 1;
	}
	r->next = L->next;
	return r;
}

void Output(Nodetype *L){
	Nodetype *p;
	p = L->next;
	printf("第%d个人的密码是%d\n",p->id,p->password);
	p = p->next;
	while(p != L->next) {
		printf("第%d个人的密码是%d\n",p->id,p->password);
		p = p->next;
    }
}
int Count(Nodetype *L){
	Nodetype *p;
	int count = 1;
	p = L;
	while(L->next != p){
		L = L->next;
		count = count + 1;
	}
	return count;
}
void YueSeFu(Nodetype *r, int m) {
	int t = m;
	Nodetype *LA = r;
	Nodetype *LB = r->next;
	while (1) {
		if (Count(LA) == 2) {
			if (t % 2 == 1) {
				printf("编号:%d 密码:%d\n\n", LB->id, LB->password);
				printf("编号:%d 密码:%d\n", LA->id, LA->password);
				break;
			} else {
				printf("编号:%d 密码:%d\n\n", LA->id, LA->password);
				printf("编号:%d 密码:%d\n", LB->id, LB->password);
				break;
			}
		} else {
			for (int i = 1; i < t; i++) {
				LA = LA->next;
				LB = LB->next; 
			}
			printf("编号:%d 密码:%d\n", LB->id, LB->password);
			if (Count(LA) == 1) {
				break;
			}
			t = LB->password;
			LB = LB->next;
			printf("\n");
			LA->next = LB;
			}
	}
}
	
int main(){
	Nodetype *L;
	int password;
	L =Creatlist();
	Output(L);
	printf("请输入初始密码:\n");
	scanf("%d",&password) ;
	YueSeFu(L,password);
	return 0;
}

你可能感兴趣的:(数据结构)