c code for linked list reverse

  • clinked-listreverse
  • write a a code for inked list reverse

    Write a program to display the contents of a linked list in reverse order.

    Code

    #include <stdio.h> #include <stdlib.h> #include <string.h> struct node { int data; struct node *next; }; void display(struct node *r) { printf("elements of list are : "); while (r) { printf("%d ---> ", r->data); r = r->next; } printf("NULL\n"); } void display_reverse(struct node *r) { int count = 0; struct node *t=r; while (r) { r = r->next; count++; } int reverse[count]; int i = 0; while (t) { reverse[i] = t->data; t = t->next; i++; } printf("%d\n",count); printf("%d\n",i); int j=count-1; printf("elements of list are : "); while (j >= 0) { printf("%d ---> ", reverse[j]); j--; } printf("NULL\n"); } struct node *create(struct node *head) { struct node *t, *p; int n; if (head == NULL) { t = (struct node *)malloc(sizeof(struct node)); printf("enter the node: \n"); scanf("%d", &t->data); t->next = NULL; head = t; } if (head != NULL) { do { t = (struct node *)malloc(sizeof(struct node)); printf("enter the node: \n"); scanf("%d", &t->data); t->next = NULL; p = head; while (p->next != NULL) { p = p->next; } p->next = t; printf("do you want to add more node press 1 for yes, 0 for no. "); scanf("%d", &n); } while (n); } return head; } int main() { struct node *head = NULL, *p; head = create(head); display(head); display_reverse(head); return 0; }