I have the following code to create one-way list of user-specified number of elements
typedef struct Node{
int val;
struct * Node next;
} Node;
int main(){
int num;
Node * prev = NULL;
Node * first = NULL;
while(scanf("%d", num) != EOF){
Node node;
node.val = num;
if(prev == NULL){
prev->next = &node;}
prev = &node;
if(first == NULL){
first = &node;}
}
}
but this seems to create 1 node and edit it each iteration
as far as I understand new()
exists only in c++, is there any way to do this without making array via malloc()
and reallocating it every iteration?
malloc
to create each new node and link to previous one. Similar as with objects created vianew
operator. So, why do you want to avoidmalloc
?malloc
just complicates the problem. Just usemalloc
, it's the most straightforward wayscanf("%d", num)
enable compiler warnings and pay attention to them.malloc
. If you can define an upper limit for the number of nodes, you could also use a static array of nodes, but in this case you might need a flag to mark a node as free or used. Or if you don't have an upper limit, you could also dynamicallyrealloc
an array of nodes. This might improve the performance if you allocate bigger chunks instead of one by one.