?
Solved

linked lists

Posted on 2003-10-21
11
Medium Priority
?
378 Views
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 ?
0
Comment
Question by:Broken_Arrow
  • 4
  • 3
  • 3
  • +1
11 Comments
 
LVL 23

Expert Comment

by:brettmjohnson
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);
      ...
}

0
 
LVL 45

Accepted Solution

by:
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
0
 

Author Comment

by:Broken_Arrow
ID: 9596528
Thanks for the hints sunny !
0
Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

 
LVL 45

Expert Comment

by:sunnycoder
ID: 9596531
:o)
0
 
LVL 4

Expert Comment

by:pankajtiwary
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.

Cheers
0
 

Author Comment

by:Broken_Arrow
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");
            exit(1);
      }
                  
      initialise(list);

      for ( ; ; )
      {      student = (struct student (*)) malloc(sizeof(struct student));
            if(student == NULL)            
            {      printf("\nMemory allocation failed");
                  exit(1);
            }                  
      
            printf("\nEnter Name & Age: ");
            if(read_data(student) == -1)
            {      printf("\nError reading data");
                  exit(1);
            }
            
            if(append_at_tail(list,student) == NULL)
            {      printf("\nError appending data");
                  exit(1);
            }            
            counter++;            
            free(student);      
            print_list(list,counter);
            printf("\nsname = %s sage = %d ",student->name,student->age);      
      }            
      free_list(list);
      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);                  
            i++;                                                            
      }
      
}

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

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

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 ?
0
 
LVL 23

Expert Comment

by:brettmjohnson
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.

WARNING: ADVANCED C PROGRAMMING FOLLOWS:

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;
      }

}

0
 
LVL 45

Expert Comment

by:sunnycoder
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
0
 
LVL 23

Expert Comment

by:brettmjohnson
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"))
      break;

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

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

    if (append_to_tail(list, student) == NULL)
      ...;
  }
0
 

Author Comment

by:Broken_Arrow
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
0
 
LVL 45

Expert Comment

by:sunnycoder
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");
              exit(1);
         }              
     
         printf("\nEnter Name & Age: ");       // read data here in that memory
         if(read_data(student) == -1)
         {     printf("\nError reading data");
              exit(1);
         }
         
         if(append_at_tail(list,student) == NULL)  // add it to list here
         {     printf("\nError appending data");
              exit(1);
         }          
         counter++;          
         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
0

Featured Post

Keep up with what's happening at Experts Exchange!

Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.

Question has a verified solution.

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

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…
Here is a helpful source code for C++ Builder programmers that allows you to manage and manipulate HTML content from C++ code, while also handling HTML events like onclick, onmouseover, ... Some objects defined and used in this source include: …
The goal of this video is to provide viewers with basic examples to understand how to use strings and some functions related to them in the C programming language.
The goal of this video is to provide viewers with basic examples to understand and use switch statements in the C programming language.
Suggested Courses

809 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