Reverse a Linked List in C with Explanation

C Program to Reverse a Linked List

#include<conio.h>
#include<stdio.h>
#include<stdlib.h>
struct node{
	int data;
	struct node *next;
	};
struct node *head=NULL;
struct node* createNode(){
	struct node *newNode = (struct node *)malloc(sizeof(struct node));
    return (newNode);
}

void insertNode(){
	struct node *temp,*ptr;
	temp=createNode();
	printf("enter the data you want to insert:");
	scanf("%d",&temp->data);
	temp->next=NULL;
	if(head==NULL)
		head=temp;
	else{
		ptr=head;
		while(ptr->next!=NULL){
			ptr=ptr->next;
		}
	    ptr->next=temp;
	}
}

void listReverse(){
	struct node *prev, *current;
	if(head!=NULL){
		prev = head;
		current = head->next;
		head = head->next;
		prev->next=NULL;
		while(head!=NULL)
		{
			head=head->next;
			current->next=prev;
			prev = current;
			current=head;
		 }
		 head=prev;
    }  
    printf("list reversed successfully");
}

void viewList(){
	struct node* temp=head;
	if(temp==NULL){
		printf("list is empty");
	}
	else{
	    printf("List items are: \n");
		while(temp->next!=NULL)
		{
			printf("%d\t",temp->data);
			temp=temp->next;
		}
		printf("%d \t",temp->data);
	}
}

int menu(){
	int choice;
	printf("\n 1.Add value to the list");
	printf("\n 2.Reverse the list");
	printf("\n 3.View the list");
	printf("\n 4. exit");
	printf("\n Please enter your choice: \t");
	scanf("%d",&choice);
	return(choice);
}
void main(){
	while(1){
		switch(menu()){
			case 1:
				insertNode();
				break;
			case 2:
				listReverse();
				break;
			case 3:
			    viewList();
			    break;
			case 4:
				exit(0);
			default:
				printf("invalid choice");
		}
		getch();
	}

}

Output:

reverse a linked list in c

Share on