One-way circular linked list:
Empty table: L->next = L.
The link to the single linked list: The method of judging the end of the table is different: single-linked list with p==null; circular list with p==l.
Two-way loop linked list: A node contains a pointer to the successor (next) and a forward (prior) two pointers, and two directions, respectively, constitute a circular chain list.
Insert and delete of two-way circular linked list:
Insert S after 1.P
S->next = p->next;
P->next = s;
S->prior = p;
S->next->prior = s;
Insert S before 2.P
S->prior= p->prior;
P->prior = s;
S->next = p;
S->prior->next = s;
3. Remove P following s
s = p->next;
P->next = s->next;
P->next->prior = p;
4. Remove P
p->prior->next= p->next;
P->next->prior= p->prior;
Circular link list--solve Josephus problem
Title: n Individuals in a circle, from the first starting from the beginning of the sequence of the three-way. All the 3 are out of the circle, and the winner is the last one left.
Use a circular link list to solve:
#include <iostream> using namespace std;
typedef struct NODE {int data;
struct Node *next;
}node,*list;
List creatlist (int n) {list head,p;
int i;
Head= (node*) malloc (sizeof (Node));
if (!head) {cout<< "memory allocation error!\n";
Exit (1); } head->data=1;
head->next=head;
for (i=n;i>1;--i) {p= (node*) malloc (sizeof (Node));
if (!p) {cout<< "memory allocation error!\n";
Exit (1); } p->data=i; p->next=head->next;
head->next=p;
} return head;
} void Output (list head) {list p=head;
Do {cout<<p->data<< "";
p=p->next;
}while (P!=head);
cout<<endl;
} void Play (list head,int n,int m)//First method {list p,q;
int c,k; P=head; C=1;
K=n;
while (k>1) {if (c==m-1) {q=p->next; p->next=q->next;
cout<<q->data<< "";
Free (q); c=0;
--k;
} else {C + +; p=p->next;}
} cout<< "The winner is" <<p->data;
cout<<endl; } void Josephus (LisT h,int n,int m)//The second method {node* p=h,*pre=null;
int i,j;
for (I=0;i<n-1;++i) {for (j=1;j<m;++j) {pre=p;
p=p->next;
} cout<< "People who are out of the box" <<p->data<<endl; pre->next=p->next;
Free (p);
p=pre->next;
} cout<< "The winner is" <<p->data<<endl;}
int main () {List head;
int n,m;
cout<< "Input The N and M:";
cin>>n>>m;
Head=creatlist (n);
Output (head);
Josephus (HEAD,N,M);
return 0; }
Execution Result: Input the N and m:10 3
1 2 3 4 5 6 7 8 9 10
The people out there are 3.
The people out there are 6.
The people out there are 9.
The people out there are 2.
The people out there are 7.
The people out there are 1.
The people out there are 8.
The people out there are 5.
The people out there are 10.
The winner is 4
Please press any key to continue ...