How can I add items into a struct without creating variables - c

I am using a struct to store a string and an integer like so:
struct movement {
char *direction;
int steps;
};
I can add items into the struct by doing this
struct movement m1= { "right",20 };
struct movement m2= { "left" ,10 };
The end result I am trying to achieve is to collect user inputs (e.g. "right 20"), and store it in the struct. How can I store an unknown number of user inputs into the struct without the use of variables (m1, m2 etc) since I will not know how many items there will be at the end.

It doesn't sound as if you really want to "store values into the struct", instead you want to store a sequence of independent struct instances; one for each user input.
The three most basic ways of doing this are:
An array, whose size you select at compile-time. It shouldn't be too hard to make it "large enough" for reasonable input
An array whose size you set (and then grow) at run-time
A linked list of structure instances
Which one to prefer depends on which you think is simplest. If at all possible, a static appeoach is always simplest. You can easily have something like
struct movement movements[10000];
at the global level, this will only cost perhaps 120 KB on a 64-bit system. Note though that this doesn't include memory for the direction strings; if those are always chosen from "right" and "left" (and perhaps "up"/"down" too) you could represent it as an enum instead:
enum direction { DIRECTION_LEFT = 0, DIRECTION_RIGHT, DIRECTION_UP, DIRECTION_DOWN };
This will make the structure "self-contained" and (on 64-bit systems) smaller since the enumeration will be smaller than a pointer.
Dynamically growing an array using realloc() isn't too hard, you could look that up easily as its often used.

Use a linked list. It is a recursive data structure which would be great for what you want.
Here is some example code I wrote a while ago that might help:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* basic linked list structure */
typedef struct node node_t;
struct node {
char *direction;
int steps;
node_t *next;
};
/* pointers to the head and tail of the list */
typedef struct {
node_t *head;
node_t *foot;
} list_t;
list_t *initialize_list(void);
list_t *insert_nodes(list_t *list, char *direction, int steps);
void free_list(list_t *list);
node_t *generate_node(void);
void print_list(list_t *list);
void exit_if_null(void *ptr, const char *msg);
int
main(int argc, char const *argv[]) {
list_t *list;
/* empty list created */
list = initialize_list();
/* inserting information one a time */
list = insert_nodes(list, "right", 20);
list = insert_nodes(list, "left", 10);
print_list(list);
/* freeing list at the end */
free_list(list);
list = NULL;
return 0;
}
/* function to insert information into a node */
list_t
*insert_nodes(list_t *list, char *direction, int steps) {
/* called generate_node() to create a new node */
node_t *new;
new = generate_node();
/* puts steps information into node */
new->steps = steps;
/* allocates space for direction string */
/* this is needed because *direction is a pointer */
new->direction = malloc(strlen(direction)+1);
/* copies direction info into node */
strcpy(new->direction, direction);
/* inserting information at the tail of the list */
new->next = NULL;
if (list->foot == NULL) {
/* first insertion into list */
list->head = list->foot = new;
} else {
list->foot->next = new;
list->foot = new;
}
/* returns modified list */
return list;
}
.* function which generates new nodes */
node_t
*generate_node(void) {
node_t *newnode;
/* create space for new node */
newnode = malloc(sizeof(*newnode));
exit_if_null(newnode, "Allocation");
/* initialize node info to nothing */
newnode->direction = NULL;
newnode->steps = 0;
return newnode;
}
/* creates the empty linked list */
list_t
*initialize_list(void) {
list_t *list;
create space for list */
list = malloc(sizeof(*list));
exit_if_null(list, "Allocation");
/* set pointers to NULL */
/* We don't want them pointing at anything yet */
list->head = list->foot = NULL;
return list;
}
/* function which prints entire list */
void
print_list(list_t *list) {
/* start at the head of the list */
node_t *curr = list->head;
while (curr) {
printf("%s %d\n", curr->direction, curr->steps);
/* steps through the list */
curr = curr->next;
}
}
/* function which frees nodes */
void
free_list(list_t *list) {
node_t *curr, *prev;
/* start at beginning of list */
curr = list->head;
/* frees nodes one at a time */
while(curr) {
prev = curr;
curr = curr->next;
free(prev);
}
/* frees entire list */
free(list);
}
/* function which checks malloc(), and whether enough space was allocated */
void
exit_if_null(void *ptr, const char *msg) {
if (!ptr) {
printf("Unexpected null pointer: %s\n", msg);
exit(EXIT_FAILURE);
}
}

Use a LinkedList to store an indefinite number of movements.
For each movement, create a node in the linked list and update the next pointer.
struct node {
struct movement m;
node* next;
}

Related

Why my clear function with selected element does not work correctly?

during working on the project to school, i find a little problem, which i do not know remove.
Problem is in fuction clear_train. When i trying to remove 1. element, function return also my element(but empty).
Here is my source code where are definitions of all functions:
(in a_train.h are a declarations and descriptions of functions)
#include "a_train.h"
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
struct car* add_car(struct car* first,const char* target) {
struct car* adder = malloc(sizeof(struct car));
struct car *current = first;
strcpy (adder->value,target);
adder->next=NULL;
if(first == NULL){
first =adder;}
else{
while (current->next != NULL) {
current = current->next;
}
current->next = adder;
}
return first ;
}
void print_train(struct car* first) {
if (first!=NULL){
while (first!=NULL){
printf("%s\n",first->value);
first=first->next;
}
}
else printf("empty list\n");
}
void cancel_train(struct car* first) {
while(first!=NULL){
struct car* canceler = first->next;
free(first);
first=canceler;
}
}
struct car* clear_train(struct car* first, const char* target) {
if(first == NULL){
return NULL;
}else if (first->next==NULL){
if(strcmp(first->value,target)==0){
free(first);
return NULL;
}else return first;
}
struct car* prev_searcher =first;
struct car* this_searcher =first;
while (this_searcher!=NULL){
if(strcmp(this_searcher->value,target)==0){
prev_searcher->next=this_searcher->next;
free(this_searcher);
}
prev_searcher=this_searcher;
this_searcher=this_searcher->next;
}
return first;
}
here is the definition of linked list:
struct car {
char value[SIZE];
struct car* next;
};
source code of main where i am calling functions:
int main(){
struct car* train = NULL;
train = add_car(train,"Presov");
train = add_car(train,"Bratislava");
train = add_car(train,"Levoca");
train = add_car(train,"Spiska Nova Ves");
train = add_car(train,"Bardejov");
train = add_car(train,"Pichne");
clear_train(train,"Presov");
print_train(train);
cancel_train(train);
return 0;
}
And finally there is output:
//there is empty node
Bratislava
Levoca
Spiska Nova Ves
Bardejov
Pichne
You are making things more difficult to remove a node from a linked list than it needs to be. While you are free to return and assign the head node each time clear_train is called, that's not really the way to do it.
Instead of passing a pointer-to-head (first) as the parameter to clear_train, pass the actual address of the head pointer, e.g.
clear_train(&train,"Presov");
That way you can manipulate the value (node) at that address directly. If the first node in the list is the one being delete, you simply update the node address held by the original pointer to the new first node and you are done.
Instead of trying to keep a previous, current and next node, simply use a pointer-to-pointer to current node. Then when the node containing target is found, you simply update the pointer at that address to the ->next node and you are done. See Linus on Understand Pointers
That reduces your clear_train function to:
void clear_train (struct car **first, const char* target) {
struct car **ppn = first; /* pointer-to-pointer to first */
struct car *pn = *first; /* pointer-to-first */
for (; pn; ppn = &pn->next, pn = pn->next) { /* iterate, find target */
if (strcmp (pn->value, target) == 0) { /* if found */
*ppn = pn->next; /* set pointer at target address = next */
free (pn); /* free node contianing target */
break;
}
}
}
Much simpler than trying to test for different cases of where the node lies.
In clear_train
when you find the car - you free the element and then you try to get to it again so the program will make you problem.
write like this
if(strcmp(this_searcher->value,target)==0){
prev_searcher->next=this_searcher->next;
free(this_searcher);
return prev_searcher}

Adapting generic code to different size of linked list in C

For a programming assignment, we've been asked to read in some data from a text file and populate a linked list with the data. Here is the example code we've been given:
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#define MAX_INPUT 20
#define EXTRA_CHARS 2
typedef struct listNode
{
int data;
struct listNode * next;
} ListNode;
typedef ListNode * ListNodePtr;
int main()
{
ListNodePtr head, new, current, previous, next;
unsigned listSize;
int i, anInt;
char str[MAX_INPUT];
listSize = 0;
head = NULL;
while (fgets(str, MAX_INPUT+EXTRA_CHARS, stdin) != NULL)
{
/* Parsing the string to int */
if(sscanf(str,"%d",&anInt) != 1)
{
sprintf(str, "Invalid input entered \n");
exit(EXIT_FAILURE);
}
/* Creating the node using malloc(...) */
if ( (new=malloc(sizeof(ListNode))) == NULL)
{
fprintf(stderr,"\nMemory Allocation for ListInsert failed!\n");
fprintf(stderr,"Aborting data entry!\n");
break;
}
current = head;
previous = NULL;
/* Search to find where in insert new list node */
while (current != NULL && current->data < anInt)
{
previous = current;
current = current->next;
}
new->data = anInt;
new->next = current;
listSize++;
if (previous == NULL)
{
head = new;
}
else
{
previous->next = new;
}
}/*End of input loop */
/* Display integers in linked list */
current = head;
while (current != NULL)
{
printf("%d\n", current->data);
current = current->next;
}
/* Deallocate memory used by list nodes */
current = head;
while (current != NULL)
{
next = current->next;
free(current);
current = next;
}
return EXIT_SUCCESS;
}
Here's the problem I have with it. In every example of linked lists I've seen so far online or in books, the definition of a linked list is given as a struct that contains only one item of data and a pointer to the next node in the list. The problem is that we've been given the following structure definitions to populate with data:
typedef struct price
{
unsigned dollars;
unsigned cents;
} PriceType;
typedef struct item
{
char itemID[ID_LEN + 1];
char itemName[MAX_NAME_LEN + 1];
PriceType prices[NUM_PRICES];
char itemDescription[MAX_DESC_LEN + 1];
ItemTypePtr nextItem;
} ItemType;
typedef struct category
{
char categoryID[ID_LEN + 1];
char categoryName[MAX_NAME_LEN + 1];
char drinkType; /* (H)ot or (C)old. */
char categoryDescription[MAX_DESC_LEN + 1];
CategoryTypePtr nextCategory;
ItemTypePtr headItem;
unsigned numItems;
} CategoryType;
typedef struct bcs
{
CategoryTypePtr headCategory; /* Pointer to the next node */
unsigned numCategories;
} BCSType;
This does not fit in with all the examples I've seen. So in the "generic" code above, do I have to do everything above, but replace the "new->data" part with, for example, "category->categoryID", and "category->categoryName" etc etc for all the members of the struct in order to populate the entire linked list with data?
Everything you need in the way of data structures was given to you. There's a top level item, BCSType, that leads to everything else. It has a linked list of categories with the head link in headCategory. And each CategoryType has a next pointer (nextCategory), and head link (headItem) to a linked list of ItemTypes, each of which has a next pointer, nextItem. You don't need to add anything to these structs and should not (and you'll get graded down if you do). Now you need to write the code that reads the data from the file and creates instances of these data structures, using the example code as a guideline for dealing with linked lists ... but you have to think, and be creative, to apply it to the three-level structure you've been given.
The vital thing here is to learn by doing. Try to write such code and don't give up, but if you truly get stuck you can, as a last resort, ask another question here ... but be very specific when you do, and include your code and error messages and all other relevant information about what you expected to happen and what actually happened instead. And be sure to learn how to use a debugger, and use it, before posting such a question.

Storing elements of a string on a Linked List [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 8 years ago.
Improve this question
I'm having a small issue here with my linked list.
I built a linked list with strings and it worked perfectly.
Now since i'm using strtok() to separate the string I need help on storing the struct separately but keeping them connected.
Hope i explained it well
for now here's what i've got:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct dict_word *word;
typedef struct node *Node;
typedef struct double_linked_list *DLL;
struct dict_word
{
char words[100];
int year[10];
char eng_synonyms[100];
char heb_synonyms[100];
};
struct node
{
word data;
Node *next;
Node *previous;
};
struct double_linked_list
{
Node *head;
Node *last;
};
char *split(char words[100])
{
int i;
char *word=strtok(words, "_#_");
char *year=strtok(NULL, "_#_");; // assigning NULL for previousely where it left off
char *definition=strtok(NULL,"_#_");
char *synonyms=strtok(NULL,"_#_");
i=atoi(year);
printf("%s\n", word);
printf("%i\n",i);
printf("%s\n", definition);
printf("%s\n", synonyms);
return 0;
}
and this is my function to insert node by having only one string:
void insert_beginning(char words[99])
{
struct node *var, *temp;
var=(struct node *)malloc(sizeof(struct node)); //explination about the (node *)
strncpy(var->data, words,99);
if (head==NULL)
{
head=var;
head->previous=NULL;
head->next=NULL;
last=head;
}
else
{
temp=var;
temp->previous=NULL;
temp->next=head;
head->previous=temp;
head=temp;
}
}
I am a bit surprised to see plain C code used to handle such abstract data in 2014.
Nevertheless, I think you should separate the actual book data from the list.
strtok will modify your initial string (inserting '\0' at the end of each token). If you want to access the various bits strtok has split the string into, you must memorize all the pointers to the tokens (word, definition, etc).
So you should create a structure to hold all this together :
typedef struct {
const char * words;
int year;
const char * definition;
const char * synonyms;
} dict_word;
Now to create a new record, you will have to make a copy of the various tokens, just like you did previously in your linked list insertion.
But this time the copy will occur sooner, using the strdup function.
dict_word * create_record (char * raw) // raw record string
{
// allocate a new object
dict_word record = (dict_word *) malloc (sizeof (record));
assert (record != NULL);
/*
* sanity checks left out for concision,
* but you should make sure your input is properly formatted
*/
// populate the fields
record->word = strdup (strtok(raw , "_#_"));
record->year = atoi (strtok(NULL, "_#_"));
record->definition = strdup (strtok(NULL, "_#_"));
record->synomyms = strdup (strtok(NULL, "_#_"));
// done
return record;
}
You will need a cleanup function to free all the memory allocated during record creation:
void delete_record (record * r)
{
// first free all strings
free (r->word);
free (r->definition);
free (r->synomyms);
// then free the object
free (r);
}
Now for the list.
Instead of mixing up the code that handles the list with the one that cares about books, you can define the list as a more independent object:
typedef struct sNode {
struct sNode * next;
struct sNode * prev;
void * data; // this will point to the linked objects
} listNode;
typedef struct
{
listNode *head;
listNode *tail; // either first/last or head/tail, but keep it consistent :)
} List;
First you will need to initialize the list:
void List_init (List * l)
{
l->head = l->tail = NULL;
}
Then you will want to add elements to it
void List_put (List * list, void * data)
{
// allocate a node
listNode * node = (listNode *) malloc (sizeof (node));
assert (node != NULL);
// store data reference
node->data = data;
// insert the node at the end of list
node->prev = list->tail;
node->next = NULL;
list->tail = node;
if (list->head == NULL) list->head = node;
}
Finally, to use all this:
// create the list
List book_list;
List_init (&book_list);
/* ... */
// create the records
char * raw_record;
while ((raw_record = read_from_database ()) != DONE_READING)
{
List_put (book_list, create_record (raw_record));
}
/* ... */
// browse the records
listNode * node;
for (node = book_list->head; node != NULL; node = node->next)
{
dict_word * record = (dict_node *) node->data;
// do whatever you want with your record
}
All this being said and done, C is inadequate at best to handle this kind of high-level data.
You could write a very much more compact, reliable and efficient equivalent in a variety of more modern languages, starting with C++.
Now if you're just a student asked by an old geezer of a professor to do some dusty C homework and hoping to get it done for you by an old geezer of a StackOverflow contributor, well... it's your lucky day.

Linked list in C - first node data incorrect and can't figure it out

I have a multithreaded C program, where one thread creates random times and numbers, and stores them in a sorted linked list, and the second thread compares the the time in the first node to the current system time and deletes the node whenever the times are equal. However, 0 0 gets added to the linked list first, and I can't find where. It's not being added in the insert function as far as I can tell. Any help would be greatly appreciated. Here is the relevant code:
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <time.h>
#include <signal.h>
pthread_mutex_t count_mutex;
/* Link list node */
struct node
{
int roomNo;
time_t time;
struct node* next;
};
void printList(struct node *node)
{
while(node!=NULL)
{
printf("%d ", node->roomNo);
printf("%d\n ", node->time);
node = node->next;
}
}
/* Function to insert a node at the beginging of the linked list */
void insert(struct node** head_ref, int new_room, time_t new_time)
{
/* allocate node */
struct node* new_node =
(struct node*) malloc(sizeof(struct node));
/* put in the data */
new_node->roomNo = new_room;
new_node->time = new_time;
/* link the old list off the new node */
new_node->next = (*head_ref);
/* move the head to point to the new node */
(*head_ref) = new_node;
MergeSort(&(*head_ref));
}
/* sorts the linked list by changing next pointers (not data) */
void MergeSort(struct node** headRef)
{
struct node* head = *headRef;
struct node* a;
struct node* b;
/* Base case -- length 0 or 1 */
if ((head == NULL) || (head->next == NULL))
{
return;
}
/* Split head into 'a' and 'b' sublists */
FrontBackSplit(head, &a, &b);
/* Recursively sort the sublists */
MergeSort(&a);
MergeSort(&b);
/* answer = merge the two sorted lists together */
*headRef = SortedMerge(a, b);
}
struct node* SortedMerge(struct node* a, struct node* b)
{
struct node* result = NULL;
/* Base cases */
if (a == NULL)
return(b);
else if (b==NULL)
return(a);
/* Pick either a or b, and recur */
if (a->time <= b->time)
{
result = a;
result->next = SortedMerge(a->next, b);
}
else
{
result = b;
result->next = SortedMerge(a, b->next);
}
return(result);
}
void FrontBackSplit(struct node* source,
struct node** frontRef, struct node** backRef)
{
struct node* fast;
struct node* slow;
if (source==NULL || source->next==NULL)
{
/* length < 2 cases */
*frontRef = source;
*backRef = NULL;
}
else
{
slow = source;
fast = source->next;
/* Advance 'fast' two nodes, and advance 'slow' one node */
while (fast != NULL)
{
fast = fast->next;
if (fast != NULL)
{
slow = slow->next;
fast = fast->next;
}
}
/* 'slow' is before the midpoint in the list, so split it in two
at that point. */
*frontRef = source;
*backRef = slow->next;
slow->next = NULL;
}
}
void * addThread(void *n)
{
struct node *llnode = n;
int i;
for(i = 0; i <4; i++)
{
pthread_mutex_lock(&count_mutex);
printf("Adding node.\n");
insert(&llnode, getRandRoom(), getRandTime());
sleep(1);
printf("the list is...\n");
printList(llnode);
pthread_mutex_unlock(&count_mutex);
}
}
struct node* head;
int main()
{
signal(SIGINT, ctrlc_catch);
pthread_t addWakeup, makeWakeup;
pthread_create(&addWakeup, NULL, addThread, (void*)&head);
pthread_create(&makeWakeup, NULL, wakeThread, (void*)&head);
pthread_join(addWakeup, NULL);
pthread_join(makeWakeup, NULL);
return 0;
}
Example output is:
Adding node.
the list is...
0 0
4000 1323882918
Adding node.
the list is...
0 0
809 1323882890
4000 1323882918
Adding node.
the list is...
0 0
809 1323882890
7617 1323882908
4000 1323882918
Adding node.
the list is...
0 0
809 1323882890
7617 1323882908
4000 1323882918
4426 1323882926
You problem is most likely due to passing address of head (i.e. ~struct node**) instead of head(i.e. struct node*) to the thread function where void * is typecast to struct node*. Change this call pthread_create(&addWakeup, NULL, addThread, (void*)&head); to pthread_create(&addWakeup, NULL, addThread, (void*)head); & next call also on similar lines. Unfortunately you were not seeing a crash in the current case. On my system I observed that initializing head to NULL was crashing the program. Similar suggestion has already been provided by #wildplasser. Try this change out and check the list printed.
Hope this helps!
Your function addthread creates a local copy llnode of its argument n, and uses a pointer to llnode to call insert(). Insert can alter llnode, but that change will only affect the local copy.
You should change addThread to take an argument of type struct node**, instead of struct node*.
While it may exist in code not shown, the code may need a call to pthread_mutex_init to initialize the mutex. It is possible that the contents of the variable count_mutex are initialized "by chance" to values that will actually work, but it would not be good to rely on that.

How to implement a linked list in C?

I am creating a linked list as in the previous question I asked. I have found that the best way to develop the linked list is to have the head and tail in another structure. My products struct will be nested inside this structure. And I should be passing the list to the function for adding and deleting. I find this concept confusing.
I have implemented the initialize, add, and clean_up. However, I am not sure that I have done that correctly.
When I add a product to the list I declare some memory using calloc. But I am thinking shouldn't I be declaring the memory for the product instead. I am really confused about this adding.
Many thanks for any suggestions,
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define PRODUCT_NAME_LEN 128
typedef struct product_data
{
int product_code;
char product_name[PRODUCT_NAME_LEN];
int product_cost;
struct product_data_t *next;
}product_data_t;
typedef struct list
{
product_data_t *head;
product_data_t *tail;
}list_t;
void add(list_t *list, int code, char name[], int cost);
void initialize(list_t *list);
void clean_up(list_t *list);
int main(void)
{
list_t *list = NULL;
initialize(list);
add(list, 10, "Dell Inspiron", 1500);
clean_up(list);
getchar();
return 0;
}
void add(list_t *list, int code, char name[], int cost)
{
// Allocate memory for the new product
list = calloc(1, sizeof(list_t));
if(!list)
{
fprintf(stderr, "Cannot allocated memory");
exit(1);
}
if(list)
{
// First item to add to the list
list->head->product_code = code;
list->head->product_cost = cost;
strncpy(list->head->product_name, name, sizeof(list->head->product_name));
// Terminate the string
list->head->product_name[127] = '/0';
}
}
// Initialize linked list
void initialize(list_t *list)
{
// Set list node to null
list = NULL;
list = NULL;
}
// Release all resources
void clean_up(list_t *list)
{
list_t *temp = NULL;
while(list)
{
temp = list->head;
list->head = list->head->next;
free(temp);
}
list = NULL;
list = NULL;
temp = NULL;
}
============================== Edited ============================
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define PRODUCT_NAME_LEN 64
// typedef struct product_data product_data_t;
typedef struct product_data
{
int product_code;
char product_name[PRODUCT_NAME_LEN];
int product_cost;
}product_data_t;
typedef struct list
{
struct list *head;
struct list *tail;
struct list *next;
struct list *current_node;
product_data_t *data;
}list_t;
void add(list_t *list, int code, char name[], int cost);
int main(void)
{
list_t *list = NULL;
list = initialize(list);
add(list, 1001, "Dell Inspiron 2.66", 1299);
add(list, 1002, "Macbook Pro 2.66", 1499);
clean_up(list);
getchar();
return 0;
}
void add(list_t *list, int code, char name[], int cost)
{
/* Allocate memory for the new product */
product_data_t *product = (product_data_t*) calloc(1, sizeof(*product));
if(!product)
{
fprintf(stderr, "Cannot allocate memory.");
exit(1);
}
/* This is the first item in the list */
product->product_code = code;
product->product_cost = cost;
strncpy(product->product_name, name, sizeof(product->product_name));
product->product_name[PRODUCT_NAME_LEN - 1] = '\0';
if(!list->head)
{
/* Assign the address of the product. */
list = (list_t*) product;
/* Set the head and tail to this product */
list->head = (list_t*) product;
list->tail = (list_t*) product;
}
else
{
/* Append to the tail of the list. */
list->tail->next = (list_t*) product;
list->tail = (list_t*) product;
}
/* Assign the address of the product to the data on the list. */
list->data = (list_t*) product;
}
If you are looking to better understand the basics of linked lists, take a look at the following document:
http://cslibrary.stanford.edu/103/LinkedListBasics.pdf
Arguably you want your list data structure to be external to the data that it stores.
Say you have:
struct Whatever
{
int x_;
}
Then your list structure would look like this:
struct Whatever_Node
{
Whatever_Node* next_
Whatever* data_
}
Ryan Oberoi commented similarly, but w/o example.
In your case the head and tail could simply point to the beginning and end of a linked-list. With a singly linked-list, only the head is really needed. At it's most basic, a linked-list can be made by using just a struct like:
typedef struct listnode
{
//some data
struct listnode *next;
}listnodeT;
listnodeT *list;
listnodeT *current_node;
list = (listnodeT*)malloc(sizeof(listnodeT));
current_node = list;
and as long as list is always pointing to the beginning of the list and the last item has next set to NULL, you're fine and can use current_node to traverse the list. But sometimes to make traversing the list easier and to store any other data about the list, a head and tail token are used, and wrapped into their own structure, like you have done. So then your add and initialize functions would be something like (minus error detection)
// Initialize linked list
void initialize(list_t *list)
{
list->head = NULL;
list->tail = NULL;
}
void add(list_t *list, int code, char name[], int cost)
{
// set up the new node
product_data_t *node = (product_data_t*)malloc(sizeof(product_data_t));
node->code = code;
node->cost = cost;
strncpy(node->product_name, name, sizeof(node->product_name));
node->next = NULL;
if(list->head == NULL){ // if this is the first node, gotta point head to it
list->head = node;
list->tail = node; // for the first node, head and tail point to the same node
}else{
tail->next = node; // append the node
tail = node; // point the tail at the end
}
}
In this case, since it's a singly linked-list, the tail is only really useful for appending items to the list. To insert an item, you'll have to traverse the list starting at the head. Where the tail really comes in handy is with a doubly-linked list, it allows you to traverse the list starting at either end. You can traverse this list like
// return a pointer to element with product code
product_data_t* seek(list_t *list, int code){
product_data_t* iter = list->head;
while(iter != NULL)
if(iter->code == code)
return iter;
iter = iter->next;
}
return NULL; // element with code doesn't exist
}
Often times, the head and tail are fully constructed nodes themselves used as a sentinel to denote the beginning and end of a list. They don't store data themselves (well rather, their data represent a sentinel token), they are just place holders for the front and back. This can make it easier to code some algorithms dealing with linked lists at the expense of having to have two extra elements. Overall, linked lists are flexible data structures with several ways to implement them.
oh yeah, and nik is right, playing with linked-lists are a great way to get good with pointers and indirection. And they are also a great way to practice recursion too! After you have gotten good with linked-list, try building a tree next and use recursion to walk the tree.
I am not writing the code here but you need to do the following:
Create and object of list, this will remain global for the length of program.
Malloc the size of product _ data _ t.
For first element (head is NULL), point head to the malloced' address.
To add next element, move to the end of list and then add the pointer of malloced address to next of last element. (The next of the last element will always be NULL, so thats how you traverse to end.)
Forget tail for a while.
If you are learning C pointer theory this is a good exercise.
Otherwise, it feels like too much indirection for code that is not generic (as in a library).
Instead of allocating a static 128 byte character string, you might want to do some more pointer practice and use an allocated exact length string that you clean up at exit.
Academically, kungfucraigs' structure looks more generic then the one you have defined.
You're calloc'ing space for your list_t struct, just pointers to list head and tail, which isn't what you want to do.
When you add to a linked list, allocate space for an actual node in the list, which is your product_data_t struct.
You're allocating the wrong chunk of memory. Instead of allocating memory for each list element, you're allocating for the list head and tail.
For simplicity, get rid of the separate structure for the head and tail. Make them global variables (the same scope they're in now) and change them to be listhead and listtail. This will make the code much more readable (you won't be needlessly going through a separate structure) and you won't make the mistake of allocating for the wrong struct.
You don't need a tail pointer unless you're going to make a doubly linked list. Its not a major element to add once you create a linked list, but not necessary either.
In memory your items are linked by pointers in the list structure
item1 -> item2
Why not make the list structure part of your item?
Then you allocate a product item, and the list structure is within it.
typedef struct product_data
{
int product_code;
char product_name[PRODUCT_NAME_LEN];
int product_cost;
struct list_t list; // contains the pointers to other product data in the list
}product_data_t;
I think u first need to Imagin back-end. Code are nothing to important. Go here and visualize back-end basic c code of all insertion.
1) Insertion at beginning Visit and scroll to get every instruction execution on back- end
And u need front and imagin Go here
Back end imagin
And All other possible insertion here.
And important thing u can use this way.
struct Node{
int data;//data field
struct Node*next;//pointer field
};
struct Node*head,*tail; // try this way
or short cut
struct Node{
int data;//data field
struct Node*next;//pointer field
}*head,*tail; //global root pointer
And << Click >> To visualize other linked list problem.
Thanks.
A demo for Singly Linked List. If you prefer, try to check Circular Linked List and Doubly Linked List.
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
int val;
struct node * next;
} node_t;
// Iterating over a list
void
print_list(node_t *head)
{
node_t *current = head;
while(current != NULL)
{
printf("%d\n", current->val);
current = current->next;
}
}
// Adding an item to the end of the list
void
push_end(node_t *head, int val)
{
node_t *current = head;
while (current->next != NULL)
{
current = current->next;
}
current->next = malloc(sizeof(node_t));
current->next->val = val;
current->next->next = NULL;
}
// Adding an item to the head of the list
void
push_head(node_t **head, int val)
{
node_t *new_node = NULL;
new_node = malloc(sizeof(node_t));
new_node->val = val;
new_node->next = *head;
*head = new_node;
}
// Removing the head item of the list
int
pop_head(node_t **head)
{
int retval = -1;
node_t *next_node = NULL;
if (*head == NULL) {
return -1;
}
next_node = (*head)->next;
retval = (*head)->val;
free(*head);
*head = next_node;
return retval;
}
// Removing the last item of the list
int
pop_last(node_t *head)
{
int retval = 0;
node_t *current = NULL;
if (head->next == NULL) {
retval = head->val;
free(head);
return retval;
}
/* get to the second to last node in the list */
current = head;
while (current->next->next != NULL) {
current = current->next;
}
/* now current points to the second to last item of the list.
so let's remove current->next */
retval = current->next->val;
free(current->next);
current->next = NULL;
return retval;
}
// Removing a specific item
int
remove_by_index(node_t **head, int n)
{
int i = 0;
int retval = -1;
node_t *current = *head;
node_t *temp_node = NULL;
if (n == 0) {
return pop_head(head);
}
for (i = 0; i < n - 1; i++) {
if (current->next == NULL) {
return -1;
}
current = current->next;
}
temp_node = current->next;
retval = temp_node->val;
current->next = temp_node->next;
free(temp_node);
return retval;
}
int
main(int argc, const char *argv[])
{
int i;
node_t * testnode;
for (i = 0; i < argc; i++)
{
push_head(&testnode, atoi(argv[i]));
}
print_list(testnode);
return 0;
}
// http://www.learn-c.org/en/Linked_lists
// https://www.geeksforgeeks.org/data-structures/linked-list/
The linked list implementation inspired by the implementation used in the Linux kernel:
// for 'offsetof', see: https://stackoverflow.com/q/6433339/5447906.
#include <stddef.h>
// See: https://stackoverflow.com/q/10269685/5447906.
#define CONTAINER_OF(ptr, type, member) \
( (type *) ((char *)(ptr) - offsetof(type, member)) )
// The macro can't be used for list head.
#define LIST_DATA(ptr, type, member) \
CONTAINER_OF(ptr, type, member);
// The struct is used for both: list head and list nodes.
typedef struct list_node
{
struct list_node *prev, *next;
}
list_node;
// List heads must be initialized by this function.
// Using the function for list nodes is not required.
static inline void list_head_init(list_node *node)
{
node->prev = node->next = node;
}
// The helper function, mustn't be used directly.
static inline void list_add_helper(list_node *prev, list_node *next, list_node *nnew)
{
next->prev = nnew;
nnew->next = next;
nnew->prev = prev;
prev->next = nnew;
}
// 'node' must be a list head or a part of a list.
// 'nnew' must not be a list head or a part of a list. It may
// be uninitialized or contain any data (even garbage).
static inline void list_add_after(list_node *node, list_node *nnew)
{
list_add_helper(node, node->next, nnew);
}
// 'node' must be a list head or a part of a list.
// 'nnew' must not be a list head or a part of a list. It may
// be uninitialized or contain any data (even garbage).
static inline void list_add_before(list_node *node, list_node *nnew)
{
list_add_helper(node->prev, node, nnew);
}
// 'node' must be part of a list.
static inline list_node *list_del(list_node *node)
{
node->prev->next = node->next;
node->next->prev = node->prev;
return node->prev;
}
Example of usage:
#include <stdio.h>
// The struct must contain 'list_node' to be able to be inserted to a list
typedef struct
{
int data;
list_node node;
}
my_struct;
// Convert 'list_node *' to 'my_struct*' that contains this 'list_node'
static inline my_struct* get_my_struct(list_node *node_ptr)
{
return LIST_DATA(node_ptr, my_struct, node);
}
void print_my_list(list_node *head)
{
printf("list: {");
for (list_node *cur = head->next; cur != head; cur = cur->next)
{
my_struct *my = get_my_struct(cur);
printf(" %d", my->data);
}
printf(" }\n");
}
// Print 'cmd' and run it. Note: newline is not printed.
#define TRACE(cmd) \
(printf("%s -> ", #cmd), (cmd))
int main()
{
// The head of the list and the list itself. It doesn't contain any data.
list_node head;
list_head_init(&head);
// The list's nodes, contain 'int' data in 'data' member of 'my_struct'
my_struct el1 = {1};
my_struct el2 = {2};
my_struct el3 = {3};
print_my_list(&head); // print initial state of the list (that is an empty list)
// Run commands and print their result.
TRACE( list_add_after (&head , &el1.node) ); print_my_list(&head);
TRACE( list_add_after (&head , &el2.node) ); print_my_list(&head);
TRACE( list_add_before(&el1.node, &el3.node) ); print_my_list(&head);
TRACE( list_del (head.prev) ); print_my_list(&head);
TRACE( list_add_before(&head , &el1.node) ); print_my_list(&head);
TRACE( list_del (&el3.node) ); print_my_list(&head);
return 0;
}
The result of execution of the code above:
list: { }
list_add_after (&head , &el1.node) -> list: { 1 }
list_add_after (&head , &el2.node) -> list: { 2 1 }
list_add_before(&el1.node, &el3.node) -> list: { 2 3 1 }
list_del (head.prev) -> list: { 2 3 }
list_add_before(&head , &el1.node) -> list: { 2 3 1 }
list_del (&el3.node) -> list: { 2 1 }
http://coliru.stacked-crooked.com/a/6e852a996fb42dc2
Of course in real life you will most probably use malloc for list elements.
In C language, we need to define a Node to store an integer data and a pointer to the next value.
struct Node{
int data;
struct Node *next;
};
To add a new node, we have a function add which has data as an int parameter. At first we create a new Node n. If the program does not create n then we print an error message and return with value -1. If we create the n then we set the data of n to have the data of the parameter and the next will contain the root as it has the top of the stack. After that, we set the root to reference the new node n.
#include <stdio.h>
struct node
{
int data;
struct node* next;
};
int main()
{
//create pointer node for every new element
struct node* head = NULL;
struct node* second = NULL;
struct node* third = NULL;
//initialize every new pointer with same structure memory
head = malloc(sizeof(struct node));
second = malloc(sizeof(struct node));
third = malloc(sizeof(struct node));
head->data = 18;
head->next = second;
second->data = 20;
second->next = third;
third->data = 31;
third->next = NULL;
//print the linked list just increment by address
for (int i = 0; i < 3; ++i)
{
printf("%d\n",head->data++);
return 0;
}
}
This is a simple way to understand how does pointer work with the pointer. Here you need to just create pointer increment with new node so we can make it as an automatic.
Go STL route. Declaring linked lists should be agnostic of the data. If you really have to write it yourself, take a look at how it is implemented in STL or Boost.
You shouldn't even keep the *next pointer with your data structure. This allows you to use your product data structure in a various number of data structures - trees, arrays and queues.
Hope this info helps in your design decision.
Edit:
Since the post is tagged C, you have equivalent implementations using void* pointers that follow the basic design principle. For an example, check out:
Documentation | list.c | list.h

Resources