i was trying to run a c program where i was trying to implement the stack data structure using linked list. my linux version is ubuntu 10.04 and while running i get the error segmentation fault(core dump) after which the program doesnot run any more on the terminal. i am giving the coding as well.]
Code:
#include<stdio.h>
#include<stdlib.h>
struct stack
{
int data;
struct stack *link;
int top;
};
typedef struct stack stack;
void push(struct stack *,int item);
int pop(struct stack *);
void display(struct stack *);
int main()
{
struct stack s;
int noofelements_push,elements_push;
int noofelements_pop;
int i,j;
printf("\n Enter no. of elements to push:");
scanf("%d",&noofelements_push);
for(i=0;i<noofelements_push;i++)
{
printf("\n Enter the elements:");
scanf("%d",&elements_push);
push(&s,elements_push);
fflush(stdin);
}
display(&s);
printf("\n Enter no. of elements to pop:");
scanf("%d",&noofelements_pop);
for(i=0;i<noofelements_pop;i++)
{
j=pop(&s);
printf("\n the poped element is:%d",j);
}
display(&s);
return (0);
}
void push(struct stack *s,int item)
{
stack *newnode,*temp;
newnode=(stack *)malloc(sizeof(stack));
newnode->data=item;
newnode->link=NULL;
if(s==NULL)
{
s=newnode;
}
else
{
temp=s;
while(temp->link!=NULL)
{
temp=temp->link;
}
temp->link=newnode;
}
}
int pop(struct stack *s)
{
stack *temp,*prev;
int i;
temp=s;
while(temp->link!=NULL)
{
prev=temp;
temp=temp->link;
}
i=temp->data;
free(temp);
prev->link=NULL;
return(i);
}
void display(struct stack *s)
{
while(s!=NULL)
{
printf("\n %d",s->data);
s=s->link;
}
}