Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- typedef struct node
- {
- int value;
- struct node *next;
- } node_t;
- node_t *new_node(int value)
- {
- node_t *node = (node_t *)malloc(sizeof(node_t));
- node->value = value;
- node->next = NULL;
- return node;
- }
- void print_list(node_t *head)
- {
- node_t *head_it = head;
- while (head_it != NULL)
- {
- printf("%d -> ", head_it->value);
- head_it = head_it->next;
- }
- printf("NULL");
- }
- node_t *append_node(node_t *head, int value)
- {
- node_t *head_it = head;
- if (head_it == NULL)
- {
- return new_node(value);
- }
- while (head_it->next != NULL)
- {
- head_it = head_it->next;
- }
- // head_it->next = NULL
- head_it->next = new_node(value);
- return head;
- }
- node_t *attach_node(node_t *head, int value)
- {
- node_t *new_head = new_node(value);
- new_head->next = head;
- return new_head;
- }
- node_t *insert_at(node_t *head, size_t index, int value)
- {
- node_t *head_it = head;
- if (index == 0)
- {
- return attach_node(head, value);
- }
- if (head_it == NULL)
- {
- // If list is empty
- return new_node(value);
- }
- for (size_t i = 0; i < index - 1 && head_it->next != NULL; i++)
- {
- head_it = head_it->next;
- }
- // i == index or head->next = NULL
- if (head_it->next == NULL)
- {
- // Raggiunto fine della lista
- head_it->next = new_node(value);
- return head;
- }
- // i = index
- // head -> headNext
- // head -> new_node(value)
- // new_node->next = head->next()
- node_t *link = head_it->next;
- head_it->next = new_node(value);
- head_it->next->next = link;
- return head;
- }
- int main(void)
- {
- node_t *head = new_node(10);
- head->next = new_node(33);
- head->next->next = new_node(100);
- print_list(head);
- printf("\n\n");
- head = attach_node(head, 66);
- head = attach_node(head, 77);
- print_list(head);
- printf("\n\n");
- head = append_node(head, 123);
- head = append_node(head, 321);
- print_list(head);
- printf("\n\n");
- head = insert_at(head, 6, 777);
- print_list(head);
- printf("\n\n");
- return 0;
- }
Add Comment
Please, Sign In to add comment