im trying to insert values in the linked list... the first insert works but the the second fail and the program stops working... i guess the problem is with the allocation.. i couldnt solve it:( sorry the code is lil bit long
[/color][/b]
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define FMAX 6
typedef struct cell *CellPtr;
typedef struct cell {
int contents; /* contents of the cell */
CellPtr next; /* next cell in the list */
} Cell;
CellPtr insert (int input, CellPtr list);
void print_list(CellPtr list);
int main()
{
char function[FMAX];
CellPtr list=NULL;
int number;
while(1)
{
printf("< ");
scanf("%s",function);
if(strcmp(function,"insert")==0)
{
scanf("%d", &number);
list=insert(number,list);
print_list(list);
}
if(strcmp(function,"print")==0)
{
print_list(list);
}
}
return 0;
}
void print_list(CellPtr list)
{
if (list==NULL)
{
printf("The list is empty!\n");
}
else
{
while(list!=NULL)
{
printf ("%d ->",list->contents);
list=list->next;
}
printf("\n");
}
}
CellPtr insert(int input, CellPtr list)
{
CellPtr new_list, current_node;
if ((new_list=(CellPtr)malloc(sizeof(CellPtr)))== NULL)
{
printf(" Memory allocation failed !\n");
exit (1);
}
new_list->contents=input;
if(list==NULL)
{
new_list->next= list;
return new_list;
}
else
{
current_node=list;
while(current_node->next!=NULL)
{
current_node=current_node->next;
}
new_list->next=current_node->next;
current_node->next=new_list;
return list;
}
}
[b][color="#FF0000"]