hi friends
i am stuck in a stack program in which pop function is not ok.
its removing element first time only, then showing error.
dont know why free is not working
i am attaching my program. any help would be appreciated.
hi friends
i am stuck in a stack program in which pop function is not ok.
its removing element first time only, then showing error.
dont know why free is not working
i am attaching my program. any help would be appreciated.
Give me a few minutes and I'll post an answer if this stinking website hold up.
ur pop function should be:
struct stack *pop (struct stack * tos) {
struct stack *temp=tos;
struct stack *pre=NULL;
while (tos->next != NULL) {
pre=tos;
tos = tos -> next;
}
printf ("element removed is %d\n",tos -> sdata);
free(tos);
if(pre==NULL)temp=NULL;
else pre->next=NULL;
return temp;
}
This is a stack, that's not a pop function. It's part of a push function. I'm stuck on one thing. Need some more time to figure it out.
Last edited by Troll_King; 10-15-2001 at 12:31 AM.
It is a stack.
It is a linked list (but not a queue) stack.
while (tos->next != NULL) {
pre=tos;
tos = tos -> next;
}
Okay, bad mornig. You add nodes to the top, yeah that's right, but I don't understand why you traversed the list.
struct stack * push(struct stack * tos, int data) {
struct stack *ptr = tos;
if (tos != NULL) {
while (tos -> next != NULL)
tos = tos -> next;
/* ~~~~~~~~~~~~~~~~~~~*/
tos -> next = (struct stack *) malloc (sizeof (struct stack));
tos = tos -> next;
tos -> next = NULL;
tos -> sdata = data;
return ptr;
}
else {
tos = (struct stack *) malloc (sizeof (struct stack));
tos -> next = NULL;
tos -> sdata = data;
return tos;
}
}
I may just be having a bad morning. Sorry if I didn't read the code correctly. I guess I just need more time this morning.
Okay, yes this is the right push. I confused myself. Actually I'm still a little lost with your pop function. I'm looking into it.Code:struct stack * push(struct stack * tos, int data) { struct stack *newp = NULL; if(tos == NULL) { newp = (struct stack *) malloc (sizeof (struct stack)); newp->next = NULL; newp->sdata = data; tos = newp; return tos; }else { newp = (struct stack *) malloc (sizeof (struct stack)); newp->sdata = data; newp->next = tos; return newp; } }
pop function called as:
Defined like:Code:if (tos == NULL) { printf ("stack empty!\n"); }else { struct stack temp = pop(&tos); printf("%d popped.\n", temp.sdata); } break;
Took a long time to figure out.Code:struct stack pop (struct stack ** tos) { //holds the return value (data) struct stack temp; //use to free the head node struct stack *freep = *tos; //reposition the head of the stack for post pop if((*tos)->next == NULL) { *tos = NULL; temp = *freep; free(freep); }else { *tos = (*tos)->next; //get data value temp = *freep; //memcpy(&temp,*freep,sizeof(struct stack)); //free head node free(freep); } return temp; }
finally i could get an errorfree program with ur efforts.
thnax guys ,