Advertisement
STANAANDREY

rev linked lst

Apr 5th, 2023 (edited)
653
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.97 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. typedef struct Node {
  5.   int inf;
  6.   struct Node *nxt;
  7. } Node;
  8.  
  9. Node* newNode(int inf, Node *lst) {
  10.   Node *node = malloc(sizeof(Node));
  11.   if (!node) {
  12.     perror("");
  13.     exit(-1);
  14.   }
  15.   node->inf = inf;
  16.   node->nxt = lst;
  17.   return node;
  18. }
  19.  
  20.  
  21.  
  22. void freeLst(Node *fi) {
  23.   Node *aux = NULL;
  24.   while (fi) {
  25.     aux = fi->nxt;
  26.     free(fi);
  27.     fi = aux;
  28.   }
  29. }
  30.  
  31. void printLst(Node *node) {
  32.   for (; node != NULL; node = node->nxt) {
  33.     printf("%d ", node->inf);
  34.   }
  35.   puts("");
  36. }
  37.  
  38. Node *revLst(Node *fi) {
  39.   Node *prev = NULL, *curr = fi, *nxt = NULL;
  40.   while (curr != NULL) {
  41.     nxt = curr->nxt;
  42.     curr->nxt = prev;
  43.     prev = curr;
  44.     curr = nxt;
  45.   }
  46.   return prev;
  47. }
  48.  
  49. int main(void) {
  50.   Node *fi = NULL;
  51.   int n;
  52.   scanf("%d", &n);
  53.   for (int x, i = 0; i < n; i++) {
  54.     scanf("%d", &x);
  55.     fi = newNode(x, fi);//add to start
  56.   }
  57.   fi = revLst(fi);
  58.   printLst(fi);
  59.   freeLst(fi);
  60.   return 0;
  61. }
  62.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement