Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- 1. Implementacja listy która przechowuje: id,tytul,autor. Implementacja funkcji, która dodaje pole i funkcje która wyświetla wszystkie pola.
- */
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #define MAX_STRING_SIZE 40
- struct list_node{
- unsigned int id;
- char tytul[MAX_STRING_SIZE];
- char autor[MAX_STRING_SIZE];
- struct list_node *next;
- } *list_pointer;
- struct list_node *create_list(unsigned int id, char *tytul, char *autor)
- {
- struct list_node *first_node = (struct list_node*)malloc(sizeof(struct list_node));
- if(first_node){
- first_node->id = id;
- strncpy(first_node->tytul, tytul, MAX_STRING_SIZE);
- strncpy(first_node->autor, autor, MAX_STRING_SIZE);
- first_node->next = NULL;
- }
- return first_node;
- }
- struct list_node *add_first(struct list_node *list_pointer, struct list_node *new_node)
- {
- new_node->next = list_pointer;
- return new_node;
- }
- struct list_node *find_spot(struct list_node *list_pointer, int id)
- {
- struct list_node *previous = NULL;
- while(list_pointer && list_pointer->id < id){
- previous = list_pointer;
- list_pointer = list_pointer->next;
- }
- return previous;
- }
- void add_in_middle_or_at_back(struct list_node *previous, struct list_node *new_node)
- {
- new_node->next = previous->next;
- previous->next = new_node;
- }
- struct list_node *add_node(struct list_node *list_pointer, unsigned int id, char *tytul, char *autor)
- {
- struct list_node *new_node = (struct list_node*)malloc(sizeof(struct list_node));
- if(new_node){
- new_node->id = id;
- strncpy(new_node->tytul, tytul, MAX_STRING_SIZE);
- strncpy(new_node->autor, autor, MAX_STRING_SIZE);
- new_node->next = NULL;
- if(list_pointer->id >= id)
- return add_first(list_pointer, new_node);
- else{
- struct list_node *previous = find_spot(list_pointer, id);
- add_in_middle_or_at_back(previous, new_node);
- }
- }
- return list_pointer;
- }
- void print_list(struct list_node *list_pointer)
- {
- while(list_pointer){
- printf("Id: %d\nTytul: %s\nAutor: %s\n", list_pointer->id, list_pointer->tytul, list_pointer->autor);
- list_pointer = list_pointer->next;
- }
- printf("\n");
- }
- int main(void)
- {
- list_pointer = create_list(1, "Ksiazka 1", "Autor 1");
- list_pointer = add_node(list_pointer, 2, "Ksiazka 2", "Autor 2");
- list_pointer = add_node(list_pointer, 4, "Ksiazka 4", "Autor 4");
- list_pointer = add_node(list_pointer, 3, "Ksiazka 3", "Autor 3");
- print_list(list_pointer);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement