Advertisement
Vladpepe

Untitled

Oct 25th, 2018
97
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.05 KB | None | 0 0
  1. //Reverse Iterative mode of a linked list      
  2. #define _CRT_SECURE_NO_WARNINGS
  3. #include "stdio.h"
  4. #include "stdlib.h"
  5.  
  6. struct Node {
  7.     int data;
  8.     struct Node* next;
  9. };
  10.  
  11. struct Node* insert(struct Node* head, int data) {  //insertion at beginning
  12.     struct Node* list = malloc(sizeof(struct Node));
  13.     list->data = data;
  14.     if (list->next != NULL) {
  15.         list->next = head;
  16.     }
  17.     head = list;
  18.     return head;
  19. }
  20.  
  21. void Print(struct Node* head) {
  22.     struct Node* temp = head;
  23.     while (temp->next != NULL) {
  24.         printf("%d ", temp->data);
  25.         temp = temp->next;
  26.     }
  27.     printf("%d ", temp->data);
  28.     printf("\n");
  29. }
  30.  
  31. struct Node* Reverse(struct Node* head) {
  32.     struct Node *current, *prev, *next;
  33.     current = head;
  34.     prev = NULL;
  35.     while (current != NULL) {
  36.         next = current->next;
  37.         current->next = prev;
  38.         prev = current;
  39.         current = next;
  40. }
  41.     head = prev;
  42.     return head;
  43. }
  44.  
  45. int main() {
  46.     struct Node* head = NULL;
  47.     head = insert(head, 2);
  48.     head = insert(head, 4);
  49.     head = insert(head, 6);
  50.     head = insert(head, 8);
  51.     Print(head);
  52.     head = Reverse(head);
  53.     Print(head);
  54. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement