SHARE
HELP

To start with, Sr2Jr’s first step is to reduce the expenses related to education. To achieve this goal Sr2Jr organized the textbook’s question and answers. Sr2Jr is community based and need your support to fill the question and answers. The question and answers posted will be available free of cost to all.

Authors:
Walter Savitch ,kenrick Mock
Chapter:
Exercise:
Programming Projects
Question:1 | ISBN:9780132846813 | Edition: 5

### Question

Write a void function that takes a linked list of integers and reverses the order of its nodes. The function will have one call-by-reference parameter that is a pointer to the head of the list. After the function is called, this pointer will point to the head of a linked list that has the same nodes as the original list but in the reverse of the order they had in the original list. Note that your function will neither create nor destroy any nodes. It will simply rearrange nodes. Place your function in a suitable test program.

C++ program code:

``````//header section
#include <iostream>
using namespace std;
// Node structure
struct Node {
int data;
Node* next;
};

// Function to insert a new node at the beginning of the linked list
void insert(Node*& head, int data) {
Node* newNode = new Node;
newNode->data = data;
}

// Function to reverse the order of nodes in the linked list
Node* prev = nullptr;
Node* next = nullptr;

while (current != nullptr) {
next = current->next; // Store the next node
current->next = prev; // Reverse the link

// Move pointers one position ahead
prev = current;
current = next;
}

head = prev; // Update the head to the new first node (previously the last node)
}

// Function to print the linked list
cout << head->data << " ";
}
cout << endl;
}

int main() {

// Print the original linked list
cout << "Original Linked List: ";

// Print the reversed linked list
cout << "Reversed Linked List: ";

return 0;
}
``````

OUTPUT OF THE PROGRAM CODE:

``````Original Linked List: 11 12 13 14
Reversed Linked List: 14 13 12 11 ``````

### Discussions

Post the discussion to improve the above solution.