Unable to reverse linked list using iteraion

#include
using namespace std;

class node{
public:
int data;
node* next;

node(int d){
	data = d;
	next = NULL;
}

};
void insertAtHead(node*&head,int data){

if(head==NULL){
	head = new node(data);
	return;
}
node*n = new node(data);
n->next = head;
head = n;

}
void print(nodehead){
while(head!=NULL){
cout<data<<"->";
head = head->next;
}
cout<<endl;
}
void reverseLl(node
head) // this is the fuction of reversing linked list
{
while(head!=NULL)
{
head->next->next=head->next;
head=head->next;
}
head=head->next;
}
int main(){
node*head = NULL;
insertAtHead(head,7);
insertAtHead(head,6);
insertAtHead(head,5);
insertAtHead(head,4);
print(head);
reverseLl(head);
print(head);
}

Hey Mohit, your reverseLI function is wrong, you haven’t written the base case also. You can refer the code snippet given below for recursive reverse function.

 node* recReverse(node *head){
    	if(head->next==NULL){
    		return head;
    	}
    	//Rec Case
    	node*temp = recReverse(head->next);
    	head->next->next = head;
    	head->next = NULL;
    	return temp;
    }

Hey, if you don’t have any further doubt on this problem then please mark this doubt as resolved :slight_smile:

1 Like