MrSoftware
- Joined Oct 29, 2013
- 2,273
Understand what I changed in your code below. Here are your exercises: (1) Draw out what the code below does on paper and understand it. (2) extend the code below to add additional nodes. (3) Move the code for adding a new node into a function such as AddNode() below, then use that to simplify your code.
I hacked your code up a bit, it's a little ugly but hopefully it will help you understand linked lists:

C:
List* AddNode(char* name, int marks)
{
// your code here to make a new node and return the ref
}
C:
#include<stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct record
{
char Name[20];
int Marks;
struct record *next; // your declaration is wrong
}List;
int main()
{
List *head = NULL; // Top of the List
List *current = NULL; // The node we're working on right now
head = (List*)malloc(sizeof(List));
printf("Allocated %lu bytes at address 0x%p\n", sizeof(List), head);
// DO NOT MODIFY HEAD! It will always point to the top of your List
current = head;
current->Marks = 20;
strcpy(current->Name,"Vajra");
current->next = NULL;
// Lets add one more node to the end of the list
current->next = (List*)malloc(sizeof(List));
printf("Allocated %lu bytes at address 0x%p\n", sizeof(List), current->next);
current = current->next;
strcpy(current->Name, "djsfantasi");
current->Marks = 49;
current->next = NULL;
// Print the whole list, starting at the top
current = head;
while(current)
{
printf(" %d ",current->Marks);
printf(" %s \n",current->Name);
current = current->next;
};
printf("\n");
// Memory for the nodes was allocated one chunk at a time, it must be cleaned up one chunk at a time
while(head)
{
current = head;
head = head->next;
printf("Freeing memory at address 0x%p\n", current);
free(current);
}
return(0);
}

Last edited: