Given pointer to the head node of a linked list, the task is to reverse the linked list.
Examples:
Input : Head of following linked list 1->2->3->4->NULL Output : Linked list should be changed to, 4->3->2->1->NULL
typedef struct node{
int data;
node *link;
} node;
node* reverseIterative(node *head){
node *next, *prev, *curr;
if(head == NULL || head->link == NULL){
return head;
}
curr = NULL;
prev = NULL;
next = head;
while(next){
curr = next;
next = next->link;
curr->link = prev;
prev = curr;
}
head = curr;
return head;
}
void reverRecursive(node *curr){
if(curr == NULL){
return;
}
if(curr->link == NULL){
head = curr;
return;
}
reverRecursive(curr->link);
curr->link->link = curr;
curr->link = NULL;
}
void reverseRecursive(node *head){
reverRecursive(head);
}
0 comments:
Post a Comment