I have been studying data structures, and I'm new to this. Here is my code for the push and pop operations.
I considered using a node=top, so that I can avoid O(n) operations for the push (i.e. finding the last node every time).
I can't seem to find a better implementation for the pop operation.
Let me know if my code is good or bad. You can be harsh. I'll take it positively and learn from it.
typedef struct stack_ {
int data;
struct stack_ *next;
}stack;
stack *push(stack *head, stack **top, int val){
//if stack is empty
if(head == NULL){
head = (stack *)malloc(sizeof(stack *));
head -> data = val;
head -> next = NULL;
*top = head; //make current node the top of stack
return head;
}
stack *newnode;
newnode = (stack *)malloc(sizeof(stack *));
(*top)->next = newnode; //append new node to what top points to
newnode -> data = val;
newnode -> next = NULL;
*top = newnode; //make current node the top of stack
return head;
}
stack *pop(stack *head, stack **top){
if(head == NULL){
printf("Stack is empty\n");
return NULL;
}
stack *cur, *prev;
cur = head;
while(cur -> next){ //Traverse to the end
prev = cur;
cur = cur -> next;
}
prev -> next = NULL;
*top = prev; //make this node the top of stack
free(cur);
return head;
}
Here's the main function:
int main ()
{
stack *head, *top;
head = top = NULL;
while(1){
int choice;
printf("1.Push\n2.Pop\n3.Exit\n");
scanf("%d", &choice);
if(choice == 3)
break;
else if(choice == 2){
head = pop(head, &top);
showstack(head);
}
else if(choice == 1){
int val;
printf("Enter the value to be pushed\n");
scanf("%d", &val);
head = push(head, &top, val);
showstack(head);
}
else
printf("Enter the correct choice\n");
}
if(head)
free(head);
if(top)
free(top);
return 0;
}
free()
should go before thereturn
, otherwise the former will not be called. – Jamal♦ Nov 4 '13 at 17:06pop()
should either bevoid
or handle an empty stack differently. It shouldn't be returningNULL
becauseNULL
is not of typestack
. – Jamal♦ Nov 4 '13 at 17:42