-
Linked list and nodes
Hi i am writing this piece of code which takes 3 field , store it into struct, but i dont know how to create the node and the function print_planet_list() should walk through the linked list and print out the outputs.
Code:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
/* the struct */
typedef struct{
char name[128];
double dist;
char description[1024];
} planet_t;
/* have to write a definition here */
typedef struct planet_node {
???; /* what to write here? */
} planet_node;
/* Print a list of planets pointed to by ptr */
void print_planet_list(planet_node *ptr){
while(ptr != NULL){
printf("%15s %10.2f %s\n",
new[i].name,
new[i].dist,
new[i].description);/* not sure if its correct */
}
printf("\n");
}
int main(){
char buf[64];
planet_node *head = NULL;
int quit = 0;
do {
printf("Enter planet name (q quits): ");
scanf("%s",buf);
if((strcmp(buf,"q")==0)){
quit = 1;
}
else{
planet_node *new = (planet_t *) malloc(sizeof(planet_t)*? ); //how do i declare ?
strcpy(???);
printf("Enter distance and description: ");
scanf(" %lf ", new[i].dist);
gets(new[i].description);
ptr->head; /* Link new node to head */
???; /* Set the head to the new node */
}
} while(!quit);
printf("Final list of planets:\n");
print_planet_list(head);
while(head != NULL){
planet_node *remove = head;
head = (*head).next;
free(remove);
}
}
my desired input is :
Enter planet name (q quits): Earth
Enter distance and description: 0.9 Friendly and hospitable
Enter planet name (q quits): Mars
Enter distance and description: 1.05 Very cosmopolitan
output:
Mars 1.05 Very cosmopolitan
Earth 0.90 Friendly and hospitable
-
Do you know how linked lists work?
If not, I suggest reading through these two links from this site:
Linked Lists in C Tutorial - Cprogramming.com
FAQ > Linked List Issues - Cprogramming.com
Code:
/* have to write a definition here */
typedef struct planet_node {
???; /* what to write here? */
} planet_node;
When you read the two links above you will learn that a node consist of a data element and a pointer to the next node. What's the data element in your case?
Code:
planet_node *new = (planet_t *) malloc(sizeof(planet_t)*? ); //how do i declare ?
Read FAQ > Casting malloc - Cprogramming.com to learn how to use malloc() in C (especially the last part about the method most experienced programmers use).
Bye, Andreas
-
well it just suffices for you to create a structure with three fields and a pointer to the next node as in:
Code:
typedef struct {
int field1, field 2, field3;
struct node *next;
}planet_node;
and you can access the members using pointers as in
Code:
planet_node->field1 = "any user input of your choice"
can this help you proceed??