'what is the difference in the following codes for Linked List in c ? How is the memory managed in both cases ?Are there any performance differences?
I am new to C. Is there different memory management in both cases like the first one stores data in the stack and the second one in heap. In the first case, is the memory allocated by the compiler. Which one is better to use?
FIRST CODE
#include <stdio.h>
#include <stdlib.h>
struct Node{
int data;
struct Node* next;
};
void printLL(struct Node* head){
printf("%d ", (*head).data);
if((*head).next!=NULL){
printLL((*head).next);
}
}
int main()
{
struct Node first, second, third;
first.data = 9;
first.next = &second;
second.data = 3;
second.next = &third;
third.data = 7;
third.next = NULL;
printLL(&first);
return 0;
}
SECOND CODE
#include <stdio.h>
#include <stdlib.h>
struct Node{
int data;
struct Node* next;
};
void printLL(struct Node* head){
printf("%d ", (*head).data);
if((*head).next!=NULL){
printLL((*head).next);
}
}
int main()
{
struct Node* first;
struct Node* second;
struct Node* third;
first = (struct Node*)malloc(sizeof(struct Node));
second = (struct Node*)malloc(sizeof(struct Node));
third = (struct Node*)malloc(sizeof(struct Node));
first->data = 9;
first->next = second;
second->data = 3;
second->next = third;
third->data = 7;
third->next = NULL;
printLL(first);
return 0;
}
if there are any resources to read from pls send the link
Solution 1:[1]
It seems that you have missed the whole point of dynamic memory data structures, of which the linked list is the one usually taught first.
By bad luck your two MREs ( [mre] ) effectively hide that benefit.
In order to see the difference yourself, please attempt to add another node to your linked lists in both cases. Note that it does not need to be accessable directly, it is sufficient if you can access it from the previous node (otherwise the concept is prevented).
Then do that 100 times more.
Details on the concept and (artificial) use cases you will find in any class material, text book or tutorial on "linked lists". I intentionally do not provide a solution here, because an elaborate example/exercise which fits smoothly into your other learning progress is more useful to you.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Yunnosch |
