Adding items to an empty linked list C - c

For a project i am expected to create an empty linked list in one function, and then use that linked list in another function to add items into it. At the moment this is my code for the empty linked list:
typedef struct node_t {
int value;
int priority;
struct node_t *next;
}node;
typedef struct priorty_linked_list {
struct name *head;
int current_size;
int max_size;
}priority_list;
typedef node *Node;
typedef priority_list *List;
Our instructor gave us the above code, so there shouldnt be anything wrong with it. Next i started with the function create:
void create(int max_terms) {
node *head = NULL;
node *next = NULL;
List *current_size = 0;
List *max_size = max_terms;
max_size = (List*)malloc(sizeof(List));
printf("The maximum size for the list is %d",max_terms);
}
I'm assuming that the next function requires me to use a return function from the create function, but im not sure how. The add function should take the queue created above as a parameter, and not work if i havent created a queue before due to memory allocation.
Any tips or advice on my above code would be greatly appreciated!
Thanks :)

I'm going to guess that in the definition of priorty_linked_list, you wanted to write:
struct node *head;
instead of:
struct name *head;
This site has a great explanation and decent implementation that can be used for reference. There are thousands of examples in the Web very similar to what you have to implement. Don't be afraid to Google it.

Related

how to fix "invalid use of undefined type" of struct type in C?

Sorry first for my bad English. I'm begginer in C, trying to make a Singly Linked List.
This is my setup of the List:
#include <stdio.h>
#include <stdlib.h>
typedef int Element;
struct
{
Element Data;
struct Node *Next;
} Node;
typedef struct Node *Position;
typedef Position List;
This is how I initialize this Struct (i dont know if this function is wrong):
void resetList(List *L)
{
*L = (struct Node *)malloc(sizeof(Node));
};
My problem is, wherever I used the (->), I will got this error
error: invalid use of undefined type ...
the compiler mark the error at any (->) in my code. For example:
int isEmpty(List L)
{
return (L->Next == 0);
};
will get the error at (->).
I know my code is so dump. Please help me. Thanks.
My problem is, wherever I used the (->), I will got this error
Your struct needs to be defined as a type and at the same time a self-referencing type, able to point at a variable which is of the same type as itself. In can be done like this:
typedef struct Node
{
Element Data;
struct Node *Next;
} Node;
Where the first Node is a struct tag, which is a name allowed to co-exist with the type name Node later defined at the } Node;.
Hiding pointers behind a typdef like typedef struct Node *Position; is horrible practice, because it achieves nothing except making the code much harder to read for everyone including yourself. There's no need for a typedef at all here, just declare a variable Node* Position.
Similarly, drop the typedef Position List;, creating new types just for the heck of it only creates clutter.
This is how I initialize this Struct (i dont know if this function is wrong):
The reason why you aren't sure, is because of all the obscure typedefs. Consider rewriting the function as:
void resetList (Node** list)
{
*list = malloc(sizeof(Node));
};
The reason why it has to be a pointer-to-pointer is explained here: Dynamic memory access only works inside function
As for what this function does, resetList is a very weird name for a function allocating a single node. I would expect it to delete the previous list if present and then maybe allocate a new node.
In general, the first declaration of struct Node is not correct. If you specify the name of the structure at the end of its declaration, you are not specifying data type, but you create only the struct variable. Therefore, the compiler doesn't know how to allocate struct Node *Next; item in your struct.
You can simply repair your code by moving the name of the structure:
typedef int Element;
struct Node
{
Element Data;
struct Node *Next;
};
typedef struct Node* Position;
typedef Position List;

Freeing a struct

I have a linked list struct on me, and I used a node struct to help me store data and know where each node is pointing to. In the creation of my list, I did this:
struct list {
struct node *Head;
struct node *Tail;
}
struct node{
int val;
struct node * next;
}
struct list create_list(){
struct list new_list;
new_list = malloc(sizeof(struct list));
}
Then, when I am trying to free the list that I malloced for, I did this
void free_list(struct list linked_list){
free(linked_list);
}
However, I realize that I may have malloced wrong, because when you malloc, you need to assign it to a pointer. When I want to free the linked_list that I originally malloced for, nothing really changes.
I think this may be because the linked_list that I sent into free() is not a pointer, thus no changes have been made. I tried adding & and * to it, but I end up getting errors....
Any tips or help is appreciated.
Edit:
Fixed Typo on the struct list.
This is hw, so I cannot change the parameters of the functions, which is what is giving me a hard time freeing the linked list I made. This is because the function free_list() cannot change its parameter into a pointer linked list, so I don't know exactly what to do.
I will also take note of when I am mallocing for the linked list in the create_list function.
Yay for passing the linked list around by value rather than on the heap for something that small.
Is this more like what you want:
struct list create_list(){
struct list new_list = { NULL, NULL };
return list;
}
void free_list(struct list linked_list){
struct node *next;
for (struct node *node = linked_list.Head; node; node = next;)
{
temp = node->next;
free(node);
}
}
Thus freeing only the list nodes that were allocated with malloc().

I'm doing womething wrong when iterating the kernel linked lists

Thanks to this awesome answer I have mostly got how the Linux kernel linked lists work. However, the code examples in the answer are not 100% clear, and based on those alone I have written some code that gives me some issues when iterating the list.
In my module, I've initialized the list as a
struct list_head list_of_somethings;
in my __init function, I initialize it like this (I don't really get how the LIST_HEAD macro has to be used):
list_of_somethings.next = &list_of_somethings;
list_of_somethings.prev = &list_of_somethings;
This is how I add an element to the list:
struct something *new_entry = kzalloc(sizeof(struct something), GFP_KERNEL);
new_entry->some_datum=1;
// other new_entry params are set
// [...]
list_add(&(new_entry->list), &list_of_somethings);
Where struct something is defined as:
struct something {
struct list_head list;
uint8_t some_datum;
// other data
// ...
};
This is how I iterate all elements in the linked list to find the one I need:
struct list_head *pos;
struct list_head *head = &list_of_somethings;
struct something *seeked = NULL;
list_for_each(pos, head) {
struct something *pos_entry = container_of(pos, struct something, list);
if (pos_entry->some_datum == 1) {
seeked = pos_entry;
break;
}
}
And this is how I free the whole list on __exit:
struct list_head *pos;
struct list_head *head = &list_of_somethings;
list_for_each(pos, head) {
struct something *pos_entry = container_of(pos, struct something, list);
// free eventual dynamically allocated structures which are fields of pos_entry
kfree(pos_entry);
}
What am I doing wrong? I get general protection faults when I try to delete the whole list, and I don't get what I expect when retrieving an element from the list. Could you please help me understand how these should be done?

How to print linked list node top to bottom

I am trying to make linked list. I can add node one by one but I could not print the linked list as i wanted. How to print linked list node from top to bottom
#include<stdio.h>
#include<stdlib.h>
struct node{
int N;
struct node *next;
};
struct node* newNode(int number, struct node *next) {
struct node *new = malloc(sizeof(*new));
new->N = number;
new->next = next;
return new;
}
void show(struct node *head){
struct node *c;
c = head;
while (c!=NULL){
printf("%d\n",c->N);
c = c->next;
}
}
int main (void ) {
struct node *head = NULL;
head = newNode(10, head);
head = newNode(20, head);
head = newNode(30, head);
head = newNode(40, head);
show(head);
return 0;
}
Output
40
30
20
10
I am trying to print node like below
10
20
30
40
How to get above output ?
Since I understand this is probably part of an excercise, I will attempt to answer it in the style of assistance, while still giving a comprehensive answer.
I let aside the fact that you insert your elements in the head - which I am not sure it is what you want to do, and I consider the question as "How to print it backwards, once I have entered the elements correctly?".
We have to examine possible solutions on this:
1) Create a method void addToTail(Node* head, int value); That traverses the list and adds elements to the tail of the list instead of the head. Side note: this operation is time costly, as it requires O(N) time complexity. About complexities, read more here. Se also this StackOverflow question.
2) You mention the term "linked list". By what you say, you do not specify if it is a singly linked, or a doubly linked. And since you have access to the node implementation, I suggest that you add a pointer to each node that points to the previous element, thus converting your singly-linked list to a doubly-linked one.
struct node{
int N;
struct node *next;
struct node *prev;
};
And, of course, you need to update this node respectively in the operations of your list - otherwise it will not work - I let this to you.
That way, you will be able to easily iterate the list backwards then in order to print the number in the order desired.
3) You could implement a function Node * reverseList(Node* head); that "reverses" a list via iteration, and then use it to print the list reversed.
And again, I let the implementation to you. Of, course, you need to consider the list state on each time, as also if you need to reverse the list in-place or return a pointer to a new, reversed list (as the function contract above indicates).
What you need to do now, is re-read your excercise brief, stop for a moment and think: "Do I really need these solutions? Is this what is requested from me?".
If you are just entering the data in the wrong order, probably not.
But if it is specifically required from you to print the list elements backwards, then you have some good hints on how to proceed.
Recursive approach works great here:
void show(struct node *c){
if (c == NULL)
return;
show(c->next);
printf("%d\n", c->N);
}

Is it a Linked list implementation?

I am just learning pointers in C and implemented a singly linked list with 3 elements. Is this the right way of approach. Even if it isn't, does the code which I have written represents a linked list?
#include <stdio.h>
struct node
{
int a;
struct node *link;
};
int main()
{
struct node first;
struct node second;
struct node third;
first.a=1;
first.link=&second;
first.link->a=2;
first.link->link=&third;
first.link->link->a=3;
printf("\n%d",first.a);
printf("\n%d",second.a);
printf("\n%d",third.a);
return 0;
}
The code you have written correctly constructs a singly linked list, but is not a general implementation of a singly linked list data structure. For this, the operations that can be applied to a linked list (for example insert an element at a given position, append an element to the end of the list or count the number of elements in the list) are abstracted out and moved into utility functions.
So, as a next step, try implementing a void append(struct node* head, int value) function that, given a pointer to the head of the list, appends a new node with the given value to the end of the list. Then, try to express the construction of your list using this function.
#include <stdio.h>
struct node
{
int a;
struct node *link;
};
int main()
{
struct node first;
struct node second;
struct node third;
first.a=1;
first.link=&second;
first.link->a = 2;
second.link=&third;
second.link->a=3;
printf("\n%d",first.a);
printf("\n%d",second.a);
printf("\n%d",third.a);
return 0;
}
//the nodes in each struct need to point to the next struct, your code was changing the original destination of first.link from pointing to second and then to third,
it cannot point to both, second contains pointer to third, third would contain pointer to fourth....

Resources