循环链表

循环链表是一种链式存储结构,它的最后一个结点指向头结点,形成一个环。因此,从循环链表中的任何一个结点出发都能找到任何其他结点。循环链表的操作和单链表的操作基本一致,差别仅仅在于算法中的循环条件有所不同。

单向循环链表

存储结构

/* c2-2.h 线性表的单链表存储结构 */
typedef struct LNode
{
	ElemType data;
	struct LNode *next;
}LNode,*LinkList;

基本操作

/* bo2-4.c 设立尾指针的单循环链表(存储结构由c2-2.h定义)的12个基本操作 */
void InitList(LinkList *L)
{	/* 操作结果:构造一个空的线性表L */
	*L=(LinkList)malloc(sizeof(struct LNode)); /* 产生头结点,并使L指向此头结点 */
	if(!*L) /* 存储分配失败 */
		exit(OVERFLOW);
	(*L)->next=*L; /* 指针域指向头结点 */
}

void DestroyList(LinkList *L)
{	/* 操作结果:销毁线性表L */
	LinkList q,p=(*L)->next; /* p指向头结点 */
	while(p!=*L) /* 没到表尾 */
	{
		q=p->next;
		free(p);
		p=q;
	}
	free(*L);
	*L=NULL;
}

void ClearList(LinkList *L) /* 改变L */
{	/* 初始条件:线性表L已存在。操作结果:将L重置为空表 */
	LinkList p,q;
	*L=(*L)->next; /* L指向头结点 */
	p=(*L)->next; /* p指向第一个结点 */
	while(p!=*L) /* 没到表尾 */
	{
		q=p->next;
		free(p);
		p=q;
	}
	(*L)->next=*L; /* 头结点指针域指向自身 */
}

Status ListEmpty(LinkList L)
{	/* 初始条件:线性表L已存在。操作结果:若L为空表,则返回TRUE,否则返回FALSE */
	if(L->next==L) /* 空 */
		return TRUE;
	else
		return FALSE;
}

int ListLength(LinkList L)
{	/* 初始条件:L已存在。操作结果:返回L中数据元素个数 */
	int i=0;
	LinkList p=L->next; /* p指向头结点 */
	while(p!=L) /* 没到表尾 */
	{
		i++;
		p=p->next;
	}
	return i;
}

Status GetElem(LinkList L,int i,ElemType *e)
{	/* 当第i个元素存在时,其值赋给e并返回OK,否则返回ERROR */
	int j=1; /* 初始化,j为计数器 */
	LinkList p=L->next->next; /* p指向第一个结点 */
	if(i<=0||i>ListLength(L)) /* 第i个元素不存在 */
	return ERROR;
	while(j<i)
	{	/* 顺指针向后查找,直到p指向第i个元素 */
		p=p->next;
		j++;
	}
	*e=p->data; /* 取第i个元素 */
	return OK;
}

int LocateElem(LinkList L,ElemType e,Status(*compare)(ElemType,ElemType))
{	/* 初始条件:线性表L已存在,compare()是数据元素判定函数 */
	/* 操作结果:返回L中第1个与e满足关系compare()的数据元素的位序。*/
	/*           若这样的数据元素不存在,则返回值为0 */
	int i=0;
	LinkList p=L->next->next; /* p指向第一个结点 */
	while(p!=L->next)
	{
		i++;
		if(compare(p->data,e)) /* 满足关系 */
			return i;
		p=p->next;
	}
	return 0;
}

Status PriorElem(LinkList L,ElemType cur_e,ElemType *pre_e)
{	/* 初始条件:线性表L已存在 */
	/* 操作结果:若cur_e是L的数据元素,且不是第一个,则用pre_e返回它的前驱,*/
	/*           否则操作失败,pre_e无定义 */
	LinkList q,p=L->next->next; /* p指向第一个结点 */
	q=p->next;
	while(q!=L->next) /* p没到表尾 */
	{
		if(q->data==cur_e)
		{
			*pre_e=p->data;
			return TRUE;
		}
		p=q;
		q=q->next;
	}
	return FALSE; /* 操作失败 */
}

Status NextElem(LinkList L,ElemType cur_e,ElemType *next_e)
{	/* 初始条件:线性表L已存在 */
	/* 操作结果:若cur_e是L的数据元素,且不是最后一个,则用next_e返回它的后继,*/
	/*           否则操作失败,next_e无定义 */
	LinkList p=L->next->next; /* p指向第一个结点 */
	while(p!=L) /* p没到表尾 */
	{
		if(p->data==cur_e)
		{
			*next_e=p->next->data;
			return TRUE;
		}
		p=p->next;
	}
	return FALSE; /* 操作失败 */
}

Status ListInsert(LinkList *L,int i,ElemType e) /* 改变L */
{	/* 在L的第i个位置之前插入元素e */
	LinkList p=(*L)->next,s; /* p指向头结点 */
	int j=0;
	if(i<=0||i>ListLength(*L)+1) /* 无法在第i个元素之前插入 */
	return ERROR;
	while(j<i-1) /* 寻找第i-1个结点 */
	{
		p=p->next;
		j++;
	}
	s=(LinkList)malloc(sizeof(struct LNode)); /* 生成新结点 */
	s->data=e; /* 插入L中 */
	s->next=p->next;
	p->next=s;
	if(p==*L) /* 改变尾结点 */
	*L=s;
	return OK;
}

Status ListDelete(LinkList *L,int i,ElemType *e) /* 改变L */
{	/* 删除L的第i个元素,并由e返回其值 */
	LinkList p=(*L)->next,q; /* p指向头结点 */
	int j=0;
	if(i<=0||i>ListLength(*L)) /* 第i个元素不存在 */
	return ERROR;
	while(j<i-1) /* 寻找第i-1个结点 */
	{
		p=p->next;
		j++;
	}
	q=p->next; /* q指向待删除结点 */
	p->next=q->next;
	*e=q->data;
	if(*L==q) /* 删除的是表尾元素 */
	*L=p;
	free(q); /* 释放待删除结点 */
	return OK;
}

void ListTraverse(LinkList L,void(*vi)(ElemType))
{	/* 初始条件:L已存在。操作结果:依次对L的每个数据元素调用函数vi() */
	LinkList p=L->next->next; /* p指向首元结点 */
	while(p!=L->next) /* p不指向头结点 */
	{
		vi(p->data);
		p=p->next;
	}
	printf("\n");
}

[1]

双向循环链表

循环链表的应用问题

Josephu问题:据说著名犹太历史学家 Josephus有过以下的故事:在罗马人占领乔塔帕特后,39 个犹太人与Josephus及他的朋友躲到一个洞中,39个犹太人决定宁愿死也不要被敌人找到,于是决定了一个自杀方式,41个人排成一个圆圈,由第1个人开始报数,每报数到第3人该人就必须自杀,然后再由下一个重新报数,直到所有人都自杀身亡为止。然而Josephus 和他的朋友并不想遵从,Josephus要他的朋友先假装遵从,他将朋友与自己安排在第16个与第31个位置,于是逃过了这场死亡游戏。 如何用循环链表来求解Josephu问题?

参考文献

  1. ^ 高一凡. 《数据结构》算法实现及解析 2004年10月第2版. 西安: 西安电子科技大学出版社. ISBN 9787560611761 (中文). 

Read other articles:

Duta Besar Kazakhstan untuk IndonesiaPetahanaSerzhan Abdykarimovsejak 2023Situs webwww.gov.kz/memleket/entities/mfa-jakarta Berikut adalah daftar duta besar Kazakhstan untuk Republik Indonesia. Nama Kredensial Selesai tugas Ref. Beibut Atamkulov 9 Maret 2012 [1][cat. 1] Askhat Orazbay 17 Oktober 2012 [2] Daniyar Sarekenov 7 Agustus 2019 [3] Serzhan Abdykarimov 8 Desember 2023 Petahana [4] Catatan ^ Berkedudukan di Kuala Lumpur. Lihat pula Daftar Du...

 

This article needs additional citations for verification. Please help improve this article by adding citations to reliable sources. Unsourced material may be challenged and removed.Find sources: List of Marathi people in the performing arts – news · newspapers · books · scholar · JSTOR (October 2015) (Learn how and when to remove this template message) Cinema and theatre Film directors Producer-Director-Screenwriter Dadasaheb Phalke known as The Fathe...

 

Questa voce sull'argomento distretti della Svizzera è solo un abbozzo. Contribuisci a migliorarla secondo le convenzioni di Wikipedia. Jura-Nord vaudoisdistrettoLocalizzazioneStato Svizzera Cantone Vaud AmministrazioneCapoluogoYverdon-les-Bains Lingue ufficialiFrancese TerritorioCoordinatedel capoluogo46°46′44.04″N 6°38′24″E / 46.778899°N 6.64°E46.778899; 6.64 (Jura-Nord vaudois)Coordinate: 46°46′44.04″N 6°38′24″E / 46.7...

Sailboat class Cygnus 20 FKCygnus 20 FKDevelopmentDesignerGeorge HinterhoellerLocationCanadaYear1963Builder(s)Hinterhoeller YachtsSkene BoatsRoleDay sailerNameCygnus 20 FKBoatDisplacement950 lb (431 kg)Draft2.75 ft (0.84 m)HullTypeMonohullConstructionFiberglassLOA20.00 ft (6.10 m)LWL17.50 ft (5.33 m)Beam7.00 ft (2.13 m)Engine typeOutboard motorHull appendagesKeel/board typecentreboardBallast140 lb (64 kg) cast ironRudder(s)transom-mo...

 

2020年夏季奥林匹克运动会波兰代表團波兰国旗IOC編碼POLNOC波蘭奧林匹克委員會網站olimpijski.pl(英文)(波兰文)2020年夏季奥林匹克运动会(東京)2021年7月23日至8月8日(受2019冠状病毒病疫情影响推迟,但仍保留原定名称)運動員206參賽項目24个大项旗手开幕式:帕维尔·科热尼奥夫斯基(游泳)和马娅·沃什乔夫斯卡(自行车)[1]闭幕式:卡罗利娜·纳亚(皮划艇)&#...

 

Міністерство надзвичайних ситуацій України Адреса: м.Київ, вул. О.Гончара, 55а Вебсторінка: http://www.mns.gov.ua/ Міністр: Балога Віктор Іванович Герб центрального апарату МНС України Прапор МНС України Штандарт Міністра надзвичайних ситуацій України Міністе́рство Україн́и з пи�...

Duché de Basse-Lotharingie(de) Herzogtum Niederlothringen 959–1190 Basse-Lotharingie (Lotharingia Inferior) vers l'an 1000 (en rose clair).Informations générales Statut Duché du Saint-Empire romain germanique Capitale Bruxelles Langue(s) Vieux néerlandaisVieux frisonVieux saxonwallonpicardlorrain Religion Christianisme Histoire et événements 959 Division du duché de Lotharingie. 1190 La diète reconnaît que l'autorité du duc se limite aux fiefs dont il est le suzerain. Ducs ...

 

Issues of racism and race relations in various countries Part of a series onDiscrimination Forms Institutional Structural Statistical Taste-based Attributes Age Caste Class Dialect Disability Genetic Hair texture Height Language Looks Mental disorder Race / Ethnicity Skin color Scientific racism Rank Sex Sexual orientation Species Size Viewpoint Social Arophobia Acephobia Adultism Anti-albinism Anti-autism Anti-homelessness Anti-drug addicts Anti-intellectualism Anti-intersex Anti-le...

 

Barack Obama's half-brother Malik ObamaBornAbon'go Malik ObamaMarch 1958 (age 66)Nairobi, British Kenya(present-day Kenya)Other namesRoyCitizenshipKenyaUnited States[1]Alma materUniversity of NairobiOccupation(s)Businessperson, former political candidateKnown forFormer President Barack Obama's half-brotherPolitical partyRepublican (since 2016)ParentBarack Obama Sr. (father)RelativesAuma Obama (sister)Barack Obama (half-brother)FamilyObama family Abon'go Malik ...

American college basketball season 2021–22 North Dakota Fighting Hawks men's basketballConferenceSummit LeagueRecord6–25 (2–16 The Summit)Head coachPaul Sather (3rd season)Assistant coaches Jamie Stevens Zach Horstman Steven Aldridge Home arenaBetty Engelstad Sioux CenterSeasons← 2020–212022–23 → 2021–22 Summit League men's basketball standings vte Conf Overall Team W   L   PCT W   L   PCT South Dakota State † 18 – 0 ...

 

Дурман Дурман звичайний (Datura stramonium) Біологічна класифікація Царство: Рослини (Plantae) Клада: Судинні рослини (Tracheophyta) Клада: Покритонасінні (Angiosperms) Клада: Евдикоти (Eudicots) Клада: Айстериди (Asterids) Порядок: Пасльоноцвіті (Solanales) Родина: Пасльонові (Solanaceae) Підродина: Solanoideae Триба: Dat...

 

Prime Minister of Australia from 1991 to 1996 This article is about the prime minister of Australia. For the British actor, see Paul Keating (actor). The HonourablePaul KeatingKeating c. 199424th Prime Minister of AustraliaIn office20 December 1991 – 11 March 1996MonarchElizabeth IIGovernors GeneralBill HaydenSir William DeaneDeputyBrian HoweKim BeazleyPreceded byBob HawkeSucceeded byJohn HowardLeader of the Labor PartyIn office19 December 1991 – 19 March 1996DeputyBrian...

南圣地亚哥Santiago do Sul市镇南圣地亚哥在巴西的位置坐标:26°38′20″S 52°41′06″W / 26.6389°S 52.685°W / -26.6389; -52.685国家巴西州圣卡塔琳娜州面积 • 总计73.562 平方公里(28.402 平方英里)海拔450 公尺(1,480 英尺)人口(2007) • 總計1,450人 • 密度19.7人/平方公里(51.1人/平方英里) 南圣地亚哥(葡萄牙语:Santiago do Sul�...

 

يفتقر محتوى هذه المقالة إلى الاستشهاد بمصادر. فضلاً، ساهم في تطوير هذه المقالة من خلال إضافة مصادر موثوق بها. أي معلومات غير موثقة يمكن التشكيك بها وإزالتها. (ديسمبر 2018) 130° خط طول 130 غرب خريطة لجميع الإحداثيات من جوجل خريطة لجميع الإحداثيات من بينغ تصدير جميع الإحداثيات من ك...

 

Paolo Hurtado 2011Informasi pribadiNama lengkap Paolo HurtadoTanggal lahir 27 Juli 1990 (umur 34)Tempat lahir Callao, PeruTinggi 174 cm (5 ft 9 in)Posisi bermain GelandangInformasi klubKlub saat ini Vitória GuimarãesNomor 16Karier senior*Tahun Tim Tampil (Gol)2017 – Vitória Guimarães 25 (11)Tim nasional2011 – Peru 34 (3) * Penampilan dan gol di klub senior hanya dihitung dari liga domestik Paolo Hurtado (lahir 27 Juli 1990) adalah seorang pemain sepak bola berkewa...

Territory that Russia gained from Sweden in the Great Northern and Russo-Swedish wars Not to be confused with Finland Proper, a historical province in the southwest of Finland. This article has multiple issues. Please help improve it or discuss these issues on the talk page. (Learn how and when to remove these messages) This article relies largely or entirely on a single source. Relevant discussion may be found on the talk page. Please help improve this article by introducing citations to add...

 

Ancient Roman arch, a landmark of Rome, Italy Arch of DrususArch of Drusus todayArch of DrususShown within Augustan RomeClick on the map for a fullscreen viewLocationRomeCoordinates41°52′25″N 12°30′04″E / 41.87361°N 12.50111°E / 41.87361; 12.50111 The Arch of Drusus is an ancient arch in Rome, Italy, close to the First Mile of the Appian Way and next to the Porta San Sebastiano. Long misidentified, it is most likely the remains of the Arch of Trajan. Histor...

 

This article needs additional citations for verification. Please help improve this article by adding citations to reliable sources. Unsourced material may be challenged and removed.Find sources: École nationale supérieure des arts décoratifs – news · newspapers · books · scholar · JSTOR (August 2018) (Learn how and when to remove this message) École nationale supérieure des Arts DécoratifsFormer entrance to the royal school of drawing under Louis...

French-born English gentleman and politician For other people named John Acton, see John Acton (disambiguation). SirJohn ActonBtPersonal detailsBorn(1736-06-03)3 June 1736Besançon, Doubs, FranceDied12 August 1811(1811-08-12) (aged 75)Palermo, Kingdom of SicilySpouseMary Ann ActonMilitary serviceAllegiance Tuscany; NaplesYears of service1775RankAdmiralBattles/warsInvasion of Algiers (1775) Sir John Acton, Bart. Born 1736 Ob. 11 August 1811. Buried at Palermo. Attributed to Giovanni ...

 

Code name for one of the zones for amphibious landings in Northern France on D-Day, June 6, 1944 Utah BeachPart of Normandy landingsU.S. soldiers landing on UtahDateJune 6, 1944LocationPouppeville, La Madeleine, Manche, FranceResult Allied victoryBelligerents  United States  United Kingdom  GermanyCommanders and leaders Raymond O. Barton J. Lawton Collins Theodore Roosevelt Jr. Karl-Wilhelm von SchliebenUnits involved VII Corps Beach 4th Infantry Division 90th Infantry Divisio...