#include<stdio.h>
#include<stdlib.h>
struct Node{
int data;
struct Node *next;
};
static int count = 0;
int printNode(struct Node *tmp){
printf("Node %d:",count);
while(tmp!=NULL){
printf("%d ",tmp->data);
tmp = tmp->next;
}
count++;
printf("\n");
}
int main(){
struct Node *a = NULL;
struct Node *b = NULL;
a = (struct Node*)malloc(sizeof(struct Node));
b = (struct Node*)malloc(sizeof(struct Node));
a->data=5;
a->next=b;
b->data=6;
b->next=NULL;
struct Node *tmp = a;
printNode(tmp);
struct Node *current = a;
struct Node *pre = NULL;
struct Node *after = NULL;
while(current!=NULL){
after = current->next;//stores forward values as tmp value
current->next = pre;//Makes forward values as NULL
pre = current;//copy the currect value as old
current = after;// not the currect will refer to forward tmp value
}
tmp = pre;
printNode(tmp);
}
I see your point now. I apologize for any confusion in my previous response. Let's go through the code
again and clarify how the linked list is reversed.
If you have a linked list with values 1, 2, 3, the reversal process will go as follows:
Initially:
1 -> 2 -> 3 -> NULL
current = 1
pre = NULL
First iteration:
after = current->next; (after = 2)
current->next = pre; (current->next = NULL)
pre = current; (pre = 1)
current = after; (current = 2)
After the first iteration:
NULL <- 1 2 -> 3 -> NULL
pre current
Second iteration:
after = current->next; (after = 3)
current->next = pre; (current->next = 1)
pre = current; (pre = 2)
current = after; (current = 3)
After the second iteration:
NULL <- 1 <- 2 3 -> NULL
pre current
Third iteration:
after = current->next; (after = NULL)
current->next = pre; (current->next = 2)
pre = current; (pre = 3)
current = after; (current = NULL)
After the third iteration:
NULL <- 1 <- 2 <- 3 NULL
pre current
Now, tmp = pre, so tmp will point to the last node in the reversed linked list:
tmp
|
v
NULL <- 1 <- 2 <- 3 NULL
pre
current
So, after this process, the linked list is indeed reversed, and tmp points to the first node of
the reversed linked list, which is the original last node. I hope this clarifies the behavior of the
code.
To embed this program on your website, copy the following code and paste it into your website's HTML: