Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Sign In with Facebook Sign In with Google Sign In with OpenID

Categories

We have migrated to a new platform! Please note that you will need to reset your password to log in (your credentials are still in-tact though). Please contact lee@programmersheaven.com if you have questions.
Welcome to the new platform of Programmer's Heaven! We apologize for the inconvenience caused, if you visited us from a broken link of the previous version. The main reason to move to a new platform is to provide more effective and collaborative experience to you all. Please feel free to experience the new platform and use its exciting features. Contact us for any issue that you need to get clarified. We are more than happy to help you.

linked list node removal

RondaneRondane Posts: 4Member
Hi all, I created a circular linked list (see the below code)from which I managed to skip the specified node(named 'candidate' in the code) and get the required solution, however I couldn't delete it using the 'free' procedure,requesting to delete the allocated memory, although it's only a copy of the pointer I work on.Can you please suggest a solution?It's much appreciated, thanks.
//The below code is a suggested solution for Josephus problem
#include
#include

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
");
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("

The linked list: ");
printCList(tmp);
printf("Please enter the 'Every which location' and the number of survivors:m k
");
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("

The %3d survivors are located at places:
", 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("

");
}
short int listLength(nodePtr pivot){
short int k;
nodePtr ptr;
for (ptr=pivot,k=1;ptr->next!=pivot;ptr=ptr->next,++k);
return k;
}








Sign In or Register to comment.