Advertisement
STANAANDREY

sda rev linked list

Jan 15th, 2024
824
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.92 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <stdbool.h>
  4.  
  5. typedef struct Node {
  6.     int data;
  7.     struct Node *nxt;
  8. } Node;
  9.  
  10. Node* newNode(int data, Node* nxt) {
  11.     Node* node = (Node*)malloc(sizeof(Node));
  12.     if (node == NULL) {
  13.         perror("");
  14.         exit(EXIT_FAILURE);
  15.     }
  16.     node->data = data;
  17.     node->nxt = nxt;
  18.     return node;
  19. }
  20.  
  21. void addToStart(Node** head, int data) {
  22.     Node* node = newNode(data, *head);
  23.     *head = node;
  24. }
  25.  
  26. void printList(Node* head) {
  27.     for (Node* node = head; node; node = node->nxt) {
  28.         printf("%d ", node->data);
  29.     }
  30.     puts("");
  31. }
  32.  
  33. void reverse(Node** head) {
  34.     Node* prev = NULL;
  35.     Node* curr = *head;
  36.     Node* nxt = NULL;
  37.     while (curr) {
  38.         nxt = curr->nxt;
  39.         curr->nxt = prev;
  40.         prev = curr;
  41.         curr = nxt;
  42.     }
  43.     *head = prev;
  44. }
  45.  
  46. int main(void) {
  47.     Node* head = NULL;
  48.     addToStart(&head, 1);
  49.     addToStart(&head, 2);
  50.     addToStart(&head, 3);
  51.     reverse(&head);
  52.     printList(head);
  53.     return 0;
  54. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement