C語言用循環(huán)單鏈表實(shí)現(xiàn)約瑟夫環(huán)
更新時(shí)間:2021年10月28日 17:09:41 作者:東流長江水
這篇文章主要為大家詳細(xì)介紹了C語言用循環(huán)單鏈表實(shí)現(xiàn)約瑟夫環(huán),文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
用循環(huán)單鏈表實(shí)現(xiàn)約瑟夫環(huán)(c語言),供大家參考,具體內(nèi)容如下
源代碼如下,采用Dev編譯通過,成功運(yùn)行,默認(rèn)數(shù)到三出局。
主函數(shù):
main.c文件
#include <stdio.h> #include "head.h" #include "1.h" int main() { Linklist L; int n; printf("請輸入約瑟夫環(huán)中的人數(shù):"); scanf("%d",&n); Createlist(L,n); printf("創(chuàng)建的約瑟夫環(huán)為:\n"); Listtrave(L,n); printf("依次出局的結(jié)果為:\n"); Solution(L,n); return 0; }
head.h文件:
#include "1.h" #include <stdio.h> #include <stdlib.h> typedef int Elemtype; typedef struct LNode{ Elemtype data; struct LNode *next; }LNode,*Linklist; void Createlist(Linklist &L,int n) { Linklist p,tail; L = (Linklist)malloc(sizeof(LNode)); L->next = L;//先使其循環(huán) p = L; p->data = 1;//創(chuàng)建首節(jié)點(diǎn)之后就先給首節(jié)點(diǎn)賦值,使得后面節(jié)點(diǎn)賦值的操作能夠循環(huán) tail = L; for(int i = 2;i <= n;i++) { p = (Linklist)malloc(sizeof(LNode)); p->data = i; p->next = L; tail->next = p; tail = p; } printf("已生成一個(gè)長度為%d的約瑟夫環(huán)!\n",n); } void Listtrave(Linklist L,int n)//遍歷函數(shù) { Linklist p; p = L; for(int i = 1;i <= n;i++) { printf("%3d",p->data); p = p->next; } printf("\n"); } int Solution(Linklist L,int n) { Linklist p,s; p = L,s = L; int count = 1; while(L) { if(count != 3) { count++;p = p->next;//進(jìn)行不等于3時(shí)的移位 } else { Linklist q; q = p;//用q保存p所指的位置,方便進(jìn)行節(jié)點(diǎn)的刪除 if(s->next->data == s->data)//當(dāng)只有一個(gè)元素的時(shí)候 { printf("%3d\n",s->data); free(s); return OK; } else//當(dāng)有兩個(gè)及兩個(gè)以上的元素的時(shí)候 { count = 1;//先將count重置為1 printf("%3d",p->data);//再打印出出局的值 while(s->next != p) { s = s->next;//將s移位到p的前驅(qū)節(jié)點(diǎn)處 } p = p->next;//使p指向自己的下一個(gè)節(jié)點(diǎn) s->next = p;//進(jìn)行刪除 free(q); } } } }
1.h文件:
#define TRUE 1 #define FALSE 0 #define OK 1 #define ERROR 0 #define INFEASIBLE -1 #define OVERFLOW -2
運(yùn)行結(jié)果:
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
基于C++中常見內(nèi)存錯(cuò)誤的總結(jié)
本篇文章是對C++中常見的內(nèi)存錯(cuò)誤進(jìn)行了總結(jié)介紹。需要的朋友參考下2013-05-05Java C++題解leetcode915分割數(shù)組示例
這篇文章主要為大家介紹了Java C++題解leetcode915分割數(shù)組示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-11-11C++ Boost MetaStateMachine定義狀態(tài)機(jī)超詳細(xì)講解
Boost是為C++語言標(biāo)準(zhǔn)庫提供擴(kuò)展的一些C++程序庫的總稱。Boost庫是一個(gè)可移植、提供源代碼的C++庫,作為標(biāo)準(zhǔn)庫的后備,是C++標(biāo)準(zhǔn)化進(jìn)程的開發(fā)引擎之一,是為C++語言標(biāo)準(zhǔn)庫提供擴(kuò)展的一些C++程序庫的總稱2022-12-12