By Arjun Tyagi
In this article, we will discuss the method and program to reverse a linked list using the C programming language.
A reverse linked list is formed by changing the links between the nodes of a linked list.The head node of the linked list will be the last node of the linked list and the last one will be the head node.
The time complexity to reverse a linked list is big-oh(n) or O(n) because we have traverse through the whole list one by one.
#include
#include struct node{ int data; struct node* next; }; //declaring a node data-type// struct node* head; void insertion(int data){ struct node* newnode=(struct node*) malloc(sizeof(struct node));//allocating memory for a node// newnode->data=data; newnode->next=NULL; if(head==NULL){ //list is empty // head=newnode; } else{ struct node* temp=head; while(temp->next!=NULL){ temp=temp->next; //traversing to the last element// } temp->next=newnode; //Storing the address of new node in previous node link part// } } void rev(){ struct node* curr; struct node* after; struct node*prev; curr=head; after=head; prev=NULL; while(after!=NULL){ after=after->next; curr->next=prev; prev=curr; curr=after; } head=prev; } void print(){ struct node* temp=head; while(temp!=NULL){ if(temp->next==NULL) printf("%d",temp->data); else printf("%d->",temp->data); temp=temp->next; } printf("\n"); } int main() { insertion(1); insertion(2); insertion(3); insertion(4); print(); rev(); print(); // your code goes here return 0; }
Submitted by Arjun Tyagi (Arjuntyagi)
Download packets of source code on Coders Packet
Comments