I have prepared a code to perform the above task:
Code:
#include <stdio.h>
#include <stdlib.h>
struct node {
int data;
struct node *ptr;
}*start = NULL, *last = NULL;
void create() {
char ch;
struct node *t, *t1;
do {
t = (struct node*)malloc(sizeof(struct node));
printf("Please Enter The Data: ");
scanf("%d", &t->data);
t->ptr = NULL;
if(start == NULL) {
start = t;
t1 = t;
} else {
t1->ptr = t;
t1 = t;
}
printf("Do you still want to insert(y/n)? ");
fflush(stdin);
scanf("%c", &ch);
}while(ch != 'n');
last = t;
}
void display() {
struct node *t;
for(t = start; start != NULL; t = t->ptr) {
printf("%d --> ", t->data);
if(t->ptr == NULL) {
break;
}
}
printf("NULL");
}
void reverse() {
struct node *t, *t1, *t2;
t2 = (struct node*)malloc(sizeof(struct node));
t = start;
for(int i = 1; t != NULL; i++) {
t1 = t;
if(i == 1) {
t = t->ptr;
t2->ptr = t->ptr;
t->ptr = t1;
t1->ptr = NULL;
} else {
t = t2->ptr;
t2->ptr = t->ptr;
t->ptr = t1;
}
}
start = last;
}
int main() {
create();
display();
reverse();
display();
}
Here the function reverse() isn't working. What I am trying to do in the reverse() function is that *t points to the current node and *t1 points to the previous node and I created *t2 as a temporary node to store the address of the next node for incrementing *t purpose. However, it is not working. Can anyone tell me what I am doing wrong?