Advertisement
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* new_node = (node_t*)malloc(sizeof(node_t*));
- new_node->value = value;
- new_node->next = NULL;
- return new_node;
- }
- void print_list(node_t* head) {
- while(head != NULL) {
- printf("%d -> ", head->value);
- head = head->next;
- }
- printf("NULL");
- }
- 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* append_node(node_t* head, int value) {
- // Head does not change
- node_t* head_it = head;
- if(head_it == NULL) {
- return new_node(value);
- }
- while(head_it->next != NULL) {
- head_it = head_it->next;
- }
- // head->null here
- head_it->next = new_node(value);
- // Return the original head
- return head;
- }
- node_t* insert_at(node_t* head, size_t index, int value) {
- // Head does not change
- node_t* head_it = head;
- if(head_it == NULL && index != 0) {
- return NULL;
- }
- for(size_t i = 0; i < index && head_it->next != NULL; i++) {
- head_it = head->next;
- }
- // i == index or head->next == NULL
- if(head_it->next == NULL) {
- // End of the list reached, adding element at the end
- head_it->next = new_node(value);
- return head;
- }
- // i == index
- 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(13);
- head->next->next = new_node(41);
- print_list(head);
- printf("\n");
- head = append_node(head, 99);
- print_list(head);
- printf("\n");
- head = attach_node(head, 12);
- print_list(head);
- printf("\n");
- head = insert_at(head, 2, 66);
- print_list(head);
- printf("\n");
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement