Given a singly linked list. The task is to replace each element of the list with the element that appears before it and replace the first element with -1.
Examples :
Input : 5->1->3->2->4 Output : -1->5->1->3->2 Input : 1->7->3->9->11->5 Output : -1->1->7->3->9->11
Approach :
Store the data of head. Initialize a pointer ptr from head->next.While traversing the list update the data of node and change the pointers and store the new previous node’s data.
Implementation :
// C++ program to replace every element of the list
// with the element that appears before it
#include <bits/stdc++.h>
using namespace std;
/* A Linked list node */
struct Node {
int data;
struct Node* next;
};
// function to insert a node at the
// beginning of the linked list
void push(struct Node** head_ref, int new_data)
{
/* allocate node */
struct Node* new_node = new Node;
/* put in the data */
new_node->data = new_data;
/* link the old list to the new node */
new_node->next = (*head_ref);
/* move the head to point to the new node */
(*head_ref) = new_node;
}
// function to replace every element of the list
// with the element that appears before it
void previousOfNodes(struct Node* &head)
{
struct Node* ptr = head->next;
int prev = head->data;
int curr;
while(ptr!=NULL){
curr = ptr->data;
ptr->data = prev;
prev = curr;
ptr = ptr->next;
}
head->data = -1;
}
void print (struct Node* &head){
while(head!=NULL){
cout<<head->data<<"--> ";
head = head->next;
}
}
// Driver program to test above
int main()
{
struct Node* head = NULL;
// create linked list 1->4->8->6->7
push(&head, 7);
push(&head, 6);
push(&head, 8);
push(&head, 4);
push(&head, 1);
previousOfNodes(head);
cout << "Updated List "<<endl;
print(head);
return 0;
}