How could I put the elements of the first LinkedList in the Reverse order in a second? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
- 1

How could I put the elements of the first LinkedList in the Reverse order in a second?

include <bits/stdc++.h> using namespace std; // A linked list node class Node { public: int data; Node *next; }; /* Given a reference (pointer to pointer) to the head of a list and an int, inserts a new node on the front of the list. */ void push(Node** head_ref, int new_data) { /* 1. allocate node */ Node* new_node = new Node(); /* 2. put in the data */ new_node->data = new_data; /* 3. Make next of new node as head */ new_node->next = (*head_ref); /* 4. move the head to point to the new node */ (*head_ref) = new_node; } /* Given a reference (pointer to pointer) to the head of a list and an int, appends a new node at the end */ void append(Node** head_ref, int new_data) { /* 1. allocate node */ Node* new_node = new Node(); Node *temp = *head_ref; /* used in step 4*/ /* 2. put in the data */ new_node->data = new_data; /* 3. This new node is going to be the last node, so make next of it as NULL*/ new_node->next = NULL; /* 4. Else traverse till the last node */ while (temp->next != NULL) { temp = temp->next; } /* 5. Change the next of last node */ temp->next = new_node; return; } // This function prints contents of // linked list starting from head void printList(Node *node) { while (node != NULL) { cout<<" "<<node->data; node = node->next;}} void createhead(Node** head_ref, int new_data) { /* 1. allocate node */ Node* new_node = new Node(); /* 2. put in the data */ new_node->data = new_data; *head_ref = new_node; return; } void printxyz(Node**head_ref){ Node*sptr=*head_ref; Node*fptr=*head_ref; while(fptr->next!=NULL) { fptr=fptr->next->next; sptr=sptr->next; } cout<<"\n The xyz element="<<sptr->data<<endl; } int main() { Node*head_firstLinkedList=NULL; createhead(&head_firstLinkedList,11); append(&head_firstLinkedList,6); push(&head_firstLinkedList,7); push(&head_firstLinkedList,1); append(&head_firstLinkedList,4); }

16th Mar 2022, 11:40 AM
Rafid
Rafid - avatar
2 Answers
+ 1
Read elements from the first linked list from beginning to end, and as you read them push each element into the second linked list (don't append them).
16th Mar 2022, 3:43 PM
Brian
Brian - avatar
16th Mar 2022, 3:50 PM
JaScript
JaScript - avatar