linked lists

Posted on 2003-10-21
Medium Priority
Last Modified: 2013-12-14
How to store data that is in the form of a structure into a list and print the contents of the list out ?
Question by:Broken_Arrow
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 4
  • 3
  • 3
  • +1
LVL 23

Expert Comment

ID: 9596464
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);

LVL 45

Accepted Solution

sunnycoder earned 1000 total points
ID: 9596471
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

Author Comment

ID: 9596528
Thanks for the hints sunny !

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

LVL 45

Expert Comment

ID: 9596531

Expert Comment

ID: 9596548
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.


Author Comment

ID: 9596555
/* 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 ?
LVL 23

Expert Comment

ID: 9596690
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;


LVL 45

Expert Comment

ID: 9596703
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
LVL 23

Expert Comment

ID: 9596859
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)

Author Comment

ID: 9597461
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
LVL 45

Expert Comment

ID: 9597475
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

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

An Outlet in Cocoa is a persistent reference to a GUI control; it connects a property (a variable) to a control.  For example, it is common to create an Outlet for the text field GUI control and change the text that appears in this field via that Ou…
This tutorial is posted by Aaron Wojnowski, administrator at SDKExpert.net.  To view more iPhone tutorials, visit www.sdkexpert.net. This is a very simple tutorial on finding the user's current location easily. In this tutorial, you will learn ho…
The goal of this video is to provide viewers with basic examples to understand and use conditional statements in the C programming language.
The viewer will learn how to use and create keystrokes in Netbeans IDE 8.0 for Windows.
Suggested Courses

801 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question