I created a circular linked list in which I successfully manage to skip a specific node at a time(denoted 'candidate' in the code) , however I couldn't remove the requested node's allocated memory using 'free' procedure.Please see the below code(I also attached the C file for your convenience).
Your help is much appreciated!
Thanks!! Ron.
Code:
#include <stdio.h>
#include <stdlib.h>
typedef struct singleNode *nodePtr ;
struct singleNode
{
short int val ;
nodePtr next ;
};
short int listLength(nodePtr);
void printCList(nodePtr);
void main(){
nodePtr member, Head, tmp=NULL, candidate=NULL;
short int len=0,i,ind,j, LIST_SIZE=0,survivors;
printf("Please define the list size,integer>=1\n");
scanf("%d",&LIST_SIZE);
for (i=1;i<=LIST_SIZE;i++){ // Building a regular linked list
member = (nodePtr) malloc(sizeof(struct singleNode)) ;
member->val = i ;
member->next = NULL ;
if ( i == 1 ){
tmp = member ;
Head = member ;
}
else{
tmp->next = member;
tmp = tmp->next ;
}
}
member->next = Head; // Turning the list into cirular one
tmp = Head;
printf("\n\nThe linked list: ");
printCList(tmp);
printf("Please enter the 'Every which location' and the number of survivors:m k\n");
scanf("%d %d", &ind, &survivors);
printf("(m=%d,k=%d)",ind, survivors);
for (j=1;listLength(tmp)>=survivors;tmp=tmp->next,j++){
if (! (j%(ind-1)) ){
candidate=tmp;
candidate->next=candidate->next->next; // skipping every m'th location
//free(candidate); // ---> doesn't work
}
if (listLength(tmp)==survivors){
printf("\n\n The %3d survivors are located at places:\n", survivors);
printCList(tmp);
break;
}
}
}//main
void printCList(nodePtr temp){ // printing a circular linked list
nodePtr head=temp;
printf("%2d ",head->val);
temp=temp->next;
while(temp!=head){
printf("%2d ",temp->val);
temp = temp->next;
}
printf("\n\n");
}
short int listLength(nodePtr pivot){
short int k;
nodePtr ptr;
for (ptr=pivot,k=1;ptr->next!=pivot;ptr=ptr->next,++k);
return k;
}