Home > Back-end >  Joseph ring problem of circular linked list
Joseph ring problem of circular linked list

Time:10-05

Joseph ring function:
Typedef struct __node
{
The int data;
Struct __node * next;
} Node, * PNode;

Void clist_josephus (int n, int m)
{
Int I=0, j=1;
Node * head=(*) malloc (sizeof (Node));
Newnode Node *=NULL, * q=head, * free_tmp;

The head - & gt; Data=https://bbs.csdn.net/topics/0;
The head - & gt; Next=NULL;
For (I=1; i {
Newnode=(*) malloc (sizeof (Node));
Newnode - & gt; Data=https://bbs.csdn.net/topics/i;
Newnode - & gt; Next=NULL;
Q - & gt; Next=newnode;
Q=newnode;
}

Q - & gt; Next=head;
While (q)
{
If (j++ & lt; M)
{
Q=q - & gt; next;
}
The else
{
Free_tmp=q - & gt; next;
Printf (" % p \ t % d \ r \ n ", free_tmp, free_tmp - & gt; The data);
Q - & gt; Next=q - & gt; Next - & gt; next;
Free (free_tmp);
Free_tmp=NULL;
J=1;
}
}
}

Why do everyone a great god, and I the complains, think impassability, why the last ring me to release, and empty will run into while the final q - & gt; Don't next and q?

CodePudding user response:

Now that is a ring, you will test the last one, q==q - & gt; The situation of the next
Delete to special treatment at this time, the q data directly, and then it is good to release the q

Your subsequent free_tmp only a data link below, the q - & gt; Next=q - & gt; Next - & gt; Next is still assigned to its itself, free function release is it

CodePudding user response:

While (q)
{
If (q==q - & gt; Next) {
//no matter how many, m is for only one node ring, eventually selected or the only node,
Printf (" % p \ t % d \ r \ n ", q, q - & gt; The data);
free(q);
Q=NULL;
} the else
If (j++ & lt; M)
{
Q=q - & gt; next;
}
The else
{
Free_tmp=q - & gt; next;
Printf (" % p \ t % d \ r \ n ", free_tmp, free_tmp - & gt; The data);
Q - & gt; Next=q - & gt; Next - & gt; next;
Free (free_tmp);
Free_tmp=NULL;
J=1;
}

CodePudding user response:

Thank you for your answer, the judgment can be resolved, but I doubt that why I will be the last node release, collocation is NULL, and it also can run into the while,

CodePudding user response:

Fun
reference 1 floor response:
now that is a ring, you are about to test the last one, q==q - & gt; The situation of the next
Delete to special treatment at this time, the q data directly, and then it is good to release the q

Your subsequent free_tmp only a data link below, the q - & gt; Next=q - & gt; Next - & gt; Next is still assigned to its itself, free function release is it

Thank you for your reply, I understand the problem, made a preconceived low-level error, at the time of the last remaining ring, actually release is q - & gt; Next is the q, but q - & gt; Next null, q was released and not to put the q is null, so he ran into the while, as for q be compared with, that have been freed and was again assignment q - & gt; Next (null), why not quit, again on the wrong operation nor in exploring the meaning of the error, thank you
  • Related