How to use a linked list in C Programming

/* 
* Program to use linked lists
* From the book: C Programming Quickstart Visual Guide
*
* By adding pointers to the definations of a structure,
* we can create a linked list of unlimited length. (well,
* limited only by the amount of available memory).
*/

#include <stdio.h>
#include <string.h> // For string functions.
#include <stdlib.h> // For memory functions.

#define STR_LEN 20

int main (void) {

/*
* Define the structure.
*/

struct student_grade {
char first_name[STR_LEN];
char last_name[STR_LEN];
float grade;
struct student_grade *next;
};

/*
* Rename the structure syntax.
*/

typedef struct student_grade sg;

/*
* Create two structure pointers.
*/

sg *first = NULL;
sg *new = NULL;
sg *temp = NULL;

int num; // For counting the input.

/*
* Need a temporary float.
*/

float g; //grade

/*
* Need some strings to handle the input.
*/

char classname[12], fn[STR_LEN], ln[STR_LEN];

/*
* Prompt the user.
*/

printf("Enter the classname (without spaces): ");
scanf("%11s", classname);

/*
* Prompt the user again.
*/

printf("Enter the student's name and their grade. Enter 0 0 0 to quite.\n(First Last ##.#): ");

/*
* Read the input.
*/

num = scanf("%11s %11s %f", fn, ln, &g);

/*
* Check if the user is done
*/

while (fn[0] != '0') {

/*
* Handle input.
*/

if (num == 3) {

new = (sg *) malloc(sizeof(sg));

/*
* Check that new is not NULL.
*/

strncpy(new->first_name, fn, STR_LEN-1);

new ->first_name[STR_LEN-1] = '\0';

strncpy(new->last_name, ln, STR_LEN-1);

new->last_name[STR_LEN-1] = '0';

new->grade = g;
new->next = first;
first = new;

} else {

printf("The data was not in the proper format.\n");
}

/*
* Prompt the user.
*/

printf("Enter the studen's name and their grade. Enter 0 0 0 to quit.\n(First Last ##.#): ");

/*
* Read the input.
*/

num = scanf("%11s %11s %f", fn, ln, &g);

} // End of while loop

/*
* Print the data and free the memory.
*/

printf("Student and grades for the class '%s':\n", classname);

new = first; //Start at the beginning.

while (new != NULL) { //Stop when list is done.

printf("%s %s %01.f\n", new->first_name, new->last_name, new->grade);

temp = new->next;
free(new);
new = temp;

}

getchar(); //Pause
getchar();//Pause
return 0;

}

Leave a Reply

Your email address will not be published. Required fields are marked *