Friday, 4 November 2016

Program 12 - Reverse a Linked List



#include <stdio.h>
struct node{
int data;
struct node *next;
};
struct node *start = NULL, *last = NULL;
void create(){
int num;
struct node *nn;
printf("Enter data: ");
scanf("%d", &num);
while(num != -1){
nn = (struct node *)malloc(sizeof(struct node));
nn -> data = num;
nn -> next = NULL;
if(start == NULL){
start = nn;
last = nn;
} else {
last -> next = nn;
last = nn;
}
printf("Enter data or enter -1 to stop: ");
scanf("%d", &num);
}
}
void reverse(){
struct node *prev = NULL, *curr = NULL;
if(start == NULL){
printf("Empty Linked list\n");
} else if(start -> next == NULL){
printf("Reversing Linked List....\n");
printf("The list has been reversed\n");
return;
} else {
printf("Reversing Linked List....\n");
/*
|start| -> |prev| -> |curr| ->......
Which logic seems ezier? This one or the one in Sorting Algorithmns
*/
prev = start -> next;
curr = prev -> next;
start -> next = NULL;
prev -> next = start;
start = prev;
while(curr != NULL){
prev = curr;
curr = curr -> next;
prev -> next = start;
start = prev;
}
printf("The list has been reversed\n");
}
}
void display(){
struct node *p;
if(start == NULL){
printf("Empty Linked list\n");
} else {
p = start;
while(p != NULL){
printf("%d ->", p -> data);
p = p -> next;
}
printf("NULL\n");
}
}
int main(){
printf("***Create Linked List***\n");
create();
system("cls");
printf("The list is: \n");
display();
reverse();
printf("The new list is: \n");
display();
}






































































































































































No comments:

Post a Comment