//expression and realization of double-chain cyclic linear table#include <stdio.h>#include<stdlib.h>#include<malloc.h>#defineTRUE 1#defineFALSE 0#defineOK 1#defineERROR 0#defineINFEASIBLE-1#defineOVERFLOW-2typedefintStatus;typedefintElemtype;typedefstructNode {elemtype data; structNode *Prior; structNode *Next;} node,*linklist;//initialize the double-chain loop linear tablevoidInitlist (Linklist &l) {L= (linklist)malloc(sizeof(node)); L->next=l->prior=l;}//get elements in a double-stranded loop linear tableNode * Getelemp_dul (linklist l,inti) {linklist P=l; if(I <1)//Illegal I value returnNULL; if(P->next = = L)//empty bidirectional loop linked list returnl; P= l->Next; intj =1;//Initialize, p points to the first node, J is the counter. while(P! = L && J < i) {//search backwards until p points to element I or P points to head nodep = p->Next; ++J; } returnp;} Status Listinsert (linklist&l,intI, Elemtype e) { //Insert Element E before the first position in the double chain loop linear table L of the lead node//the legal value of I is 1 <= i <= table length + 1Linklist p =NULL; if(! (p = Getelemp_dul (L, i)))//insert S before p node returnERROR; linklist s= (linklist)malloc(sizeof(node)); S->data =e; S->prior = p->prior; P->prior->next =s; S->next = p; P->prior =s; returnOK;}//Delete ElementStatus Listdelete_dul (Linklist &l,intI, Elemtype &e) {//in the double-chain linear table L of the lead node, delete the element I, and return its value by e//the legal value of I is 1 <= i <= table length structNode *p =NULL; if(! (P = Getelemp_dul (L, i)) | | L = =Getelemp_dul (L, i))returnERROR; E= p->data; P->prior->next = p->Next; P->next->prior = p->Prior; Free(p);returnOK;}//traversing a linear tableStatus Listtraverse_dul (linklist L, status (*Visit) (Elemtype)) {printf ("Traverse list:"); structNode *p = l->next;//A little over the knot. while(P! =L) {Visit (P-data); P= p->Next; } returnOK;}//accessing elements in a linear tablestatus Visit (Elemtype e) {printf ("%d", E); returnOK;}//test functionintMain () {linklist L; Elemtype e; Initlist (l); Linklist P=l; for(intI=1; i<=Ten; i++) Listinsert (l,i,i); Listtraverse_dul (L, Visit);//A cumbersome way to traverse a listP=p->next;//A simple way to traverse a linear table while(p!=l) {printf ("%d",p->data); P=p->Next; }//End}
Bidirectional linked list templates