linked list node removal - Programmers Heaven

Howdy, Stranger!

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

Categories

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.