Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //Write a function that appends a new node containing int i at the end of a singly linked list.
- #include <stdbool.h>
- #include <stdio.h>
- #include <stdlib.h>
- #define SIZE 10
- typedef struct node
- {
- // the n to store in this node
- int n;
- // the link to the next node in the list
- struct node* next;
- }
- node;
- node* head = NULL;
- void append(int i)
- {
- node *newNode = malloc(sizeof(node));
- if(newNode == NULL)
- {
- fprintf(stderr, "Unable to allocate memory for new node\n");
- exit(-1);
- }
- newNode->n = i;
- newNode->next = NULL; // Change 1
- //check for first insertion
- if(head->next == NULL)
- {
- head->next = newNode;
- }
- else
- {
- //else loop through the list and find the last
- //node, insert next to it
- node *current = head;
- while (true) { // Change 2
- if(current->next == NULL)
- {
- current->next = newNode;
- printf("added later\n");
- break; // Change 3
- }
- current = current->next;
- };
- }
- }
- int main(void)
- {
- // creating list
- printf("Appending ints 0-%i onto the list...\n", SIZE - 1);
- for (int i = 0; i < SIZE; i++)
- {
- append(i);
- }
- printf("done!\n");
- // printing out list
- printf("Your list contains ");
- for (node* ptr = head; ptr != NULL; ptr = ptr->next)
- {
- printf("%i ", ptr->n);
- }
- printf("\n");
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement