linked lists

How to store data that is in the form of a structure into a list and print the contents of the list out ?
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

struct data {
      struct data * next;      /* next item in linked list */
      int anInt;                  /* integer data */
      char *aString;            /* string data */

struct data * list = NULL;

      struct data *newItem, *temp;
      /* add our new item to the list (easiest to push on head) */
      newItem->next = list;
      list = newItem;
      /* print out all items in list */
      for (temp = list; temp; temp = temp->next)
            printf ("Item IntData = %d    StringData = %s\n", temp->anInt, temp->aString);

looks like home work

here are a few hints

to create a linked list you need a member of the struct which can point to another such struct
something like

struct mystruct
   //data elements here
   struct mystruct * next;

here next can point to the next element in the linked list and hence will form the links in the linked list

we need to maintain the address of the first node of the linked list ... this will be our access point to the list

to print the elements of the list, follow the address of the first node and print its data ...
next follow the next pointer in the first node and reach second node
continue doing this until you reach the end of the list
last node of the list must have next element set to NULL

now try to code it on your own and ask a specific question if you are stuck

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Broken_ArrowAuthor Commented:
Thanks for the hints sunny !
Cloud Class® Course: Amazon Web Services - Basic

Are you thinking about creating an Amazon Web Services account for your business? Not sure where to start? In this course you’ll get an overview of the history of AWS and take a tour of their user interface.

Looks exactly like a home work. A few hints can be given. A linked list is a collection of structures (called nodes) which are attached such that where you can't access a node without accessing a previous node. The structure can be defined as:

struct node {
     int data;                    /* integer data, can be anything*/
     struct node * next;     /* POINTER to the next node in linked list */

Here you have to cosider one thing, the INITIALIZATION. Actually for easy operations, there is a trick to put a dummy node at the start, it will help you write a very small function for insertion at any position, otherwise, you have to write 2 functions for insert into the list.

1. If the new item is inserted at the front
2. Any position other than the first position.

If you initialize the list with a "dummy header node", there will be only one function. Define a pointer variable as

struct node* List;

List initializelist(struct node* List) {
    List->next = (struct node*)malloc(sizeof(struct node));
    List->next->next = NULL;

After this initialization, you can proceed with the insertion part and printing part. You start, and we will help you.

Broken_ArrowAuthor Commented:
/* Name: Campbell Star */
/* User Name: cjsta */
/* ID: 300181102 */

/* This program prompts for a name and age from the keyboard until quit is
input. It places the name and age that are read from the keyboard into a
structure, the structures address is the stored at the end of the list.
After each insertion of a name and age the contents of the list is printed
to the screen.

The fundamentals associated with this program is the readability of the code,
assignment statements, function prototypes, passing by reference, defining
constants, return statments, structures and passby value.

I learnt how to create a linked list, insert data into the list and display
the list contents.

#include <stdio.h>
#include <stdlib.h>
#include <list.h>
#include <string.h>

/* character array size */
#define NAME_SIZE 20

/* Structure Definition */
struct student
{      char name[NAME_SIZE];
      int age;
      struct student *next;      

/* Function Prototypes */
int read_data(struct student *s);
void print_list(struct list *list, int );
void terminate(char *);

/*Function Definitions */
int main(void)
{      int counter = 0;      
      struct list *list = NULL;      
      struct student *student = NULL;                  

      list = create_list();
      if (list == NULL)
      {      printf("\nError: create_list() failied");

      for ( ; ; )
      {      student = (struct student (*)) malloc(sizeof(struct student));
            if(student == NULL)            
            {      printf("\nMemory allocation failed");
            printf("\nEnter Name & Age: ");
            if(read_data(student) == -1)
            {      printf("\nError reading data");
            if(append_at_tail(list,student) == NULL)
            {      printf("\nError appending data");
            printf("\nsname = %s sage = %d ",student->name,student->age);      
      return 0;

void print_list(struct list *list, int counter)
{      int i = 0;
      struct student *data = NULL;      
      for (data = goto_head(list); data != NULL; data = goto_next(list))      
      {      if(i > 0)
            {      printf(", ");
            printf("%s %d", data->name,data->age);                  

int read_data(struct student *s)
{      int match = 0;
      match = scanf("%s", s->name);
      match = scanf("%d", &s->age);

      return match;      
void terminate(char *name)
{      if(!strcmp(name, "quit"))

This is what I have attempted by myself!
but it doesn't work it prints the age but not the name,
am I scanning the name in wrong or not storing it correctly ?
pankajtiwary says:
> Actually for easy operations, there is a trick to put a dummy node at the start,
> it will help you write a very small function for insertion at any position, otherwise,
> you have to write 2 functions for insert into the list.

You do not need to put dummy nodes in a linked list to aid inserts.
And you certainly don't need two insert functions.


Consider the simplistic example I gave above.  However, we want to maintain an
ordered linked list sorted by the integer data value.

struct data {
      struct data * next;   /* next item in linked list */
      int anInt;               /* integer data */
      char *aString;         /* string data */

struct data * list = NULL;

/* insert the new node in the ordered list */
void listInsert (struct data * newNode) {

      if (newNode) {
            struct data *prevlnk, *node;

            /* locate insertion point into list ordered by anInt, increasing */
            for (prevlnk = &list, node = list; node && (node->anInt < newNode->anInt); prevlnk = &node->next, node = node->next);

            /* insert the new node in the list */
            newNode->next = node;
            *prevlnk = newNode;


scanning and printing looks OK
can you tell me what is the error you faced ?

or it could be due to the buffering of I/O routines ... try flushing the buffers before priniting / scanning ... man fflush
I noticed several problems with your code.
You misunderstood the instructions.

The goal is to request names and ages in a loop,
creating new records, and adding those new records
to the linked list.  The user signals the end of the input
process by entering "quit".

After you have added all the records to the list, print
out the list.

Your program prints the entire list each time you add a new
entry and exits on the quit command.

Although you don't provide the actual list code, I think you
will find the variable "counter" serves no valid purpose.

Unless append_at_tail() makes a deep copy of the student
record which gets added to the list, you probably do not want to
free the student structure after adding it to the list.

With scanf("%s", s->name), you run the risk of overrunning the
name buffer if the user types a name that is too long.  I also don't
think you will be happy with its tokenization.  I suggest
you use fgets() instead.  Prompt for the name and age separately
and avoid allocating a new student structure on "quit"

  static char buffer[4096];

  while (1) {
    puts("Name: ");
    fgets(buffer, sizeof(buffer), STDIN);

    if (!stricmp(buffer, "quit"))

    if ((s = (student *)malloc(sizeof(student))) == NULL)

    strncpy(student->name, buffer, NAME_SIZE);
    puts("Age: ");
    scanf("%d", &student->age); //* maybe validate age

    if (append_to_tail(list, student) == NULL)
Broken_ArrowAuthor Commented:
It all compies fine and run but when I enter a name and age the age, the name is not displayed but the age is you will have to explain a bit more for the clearing the buffers ? If I put the free(student); statement out of the for loop then it works fine is this what I want it to do?
Thanks for all your help
ofcourse that is a major error

  student = (struct student (*)) malloc(sizeof(struct student)); //you allocate memory here
         if(student == NULL)          
         {     printf("\nMemory allocation failed");
         printf("\nEnter Name & Age: ");       // read data here in that memory
         if(read_data(student) == -1)
         {     printf("\nError reading data");
         if(append_at_tail(list,student) == NULL)  // add it to list here
         {     printf("\nError appending data");
         free(student);     // deallocate that memory before printing it

free should be called after you have done with all operations with that memory/variable and need it no more
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Editors IDEs

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.