Reverse a linked list without changing links between nodes (Data reverse only)
March 17, 2023
Reverse a linked list without changing links between nodes
Reverse a linked list without changing links between nodes. What do you mean by that? We don’t have to change the links in between nodes we just have to change the matter or number over there with the other number in a linked list for the purpose of reversal.
We have to change the data, in the same way we done it in a diagram we can say that To make thing’s work we have to take two pointer’s that is left pointer and right pointer. Left pointer points to the 0th node and the right pointer points to the last node left node. In the continuation on this page we will learn about algorithm and a java program.
Algorithm to reverse a linked list Data.
Step 1– Initialize a class.
Step 2– make head as null.
Step 3-assign tail=null also.
Step 4– A function to find the size of linked list i.e (this.size).
Step 5– Further check whether linked list is empty, (this.size() ==0).
Step 6– Traverse the node and print the linked list (node temp = head)
Step 7-print (temp.data).
Step 8– temp = temp.next
Step 9 – print (“End”).
Step 10– First add a node in at the beginning of linked list.
Step 11– create a temp node which points towards head
Step 12– Then find if the linked list is empty.
Step 13– if it’s not then set the head such that it now points to temp node.
Step 14– Furthermore add a node at any index
Step 15– Throw new exception (“Index out of bound”)
Step 16– return temp
Step 17– take the left and right nodes to be swapped
}
}
struct node* reverse(struct node* head)
{
struct node* temp=head;
struct node *nodes;
struct node* exp;
int n=6;
int i; //reverse the data of the linked list//
for(i=1;i<=3;i++) //three times running
{
int j;
nodes=temp;
for(j=i;jlink;
//in c//
#include
#include
//reverse a linked list//
struct node{
int val;
struct node* link;
};
struct node* insert(struct node* head,int val)
{
struct node* node=(struct node*)malloc(sizeof(struct node));
node->val=head->val;
node->link=head->link;
head->val=val;
head->link=node;
return head;
}
void display(struct node* head)
{
struct node* nodes=head;
while( nodes != NULL)
{
printf(“%d”,nodes->val);
nodes=nodes->link;
}
}
struct node* reverse(struct node* head)
{
struct node* temp=head;
struct node *nodes;
struct node* exp;
int n=6;
int i; //reverse the data of the linked list//
for(i=1;i<=3;i++) //three times running
{
int j;
nodes=temp;
for(j=i;jlink;
}
exp->val=temp->val;
temp->val=nodes->val;
nodes->val=exp->val;
–n;
temp=temp->link;
}
return head;
}
int main()
{
struct node * head =(struct node*)malloc(sizeof(struct node));
head->val=12;
head->link=NULL;
insert(head,34);
insert(head,78);
insert(head,56);
insert(head,67);
insert(head,60);
reverse(head);
display(head);
}