Question: Reverse a Singly Linked List In c++, For this lab you are required to write a member function for a list class which will effectively
Reverse a Singly Linked List
In c++, For this lab you are required to write a member function for a list class which will effectively reverse the linked list. Please use function template provided to complete this lab.
Ex. If you list looks like this: 2 -> 15 -> 6 -> 1 Your function would alter the list to look like this: 1 -> 6 -> 15 -> 2
#include
using namespace std;
// Assume you have the following structures. Feel free to add extra helper
// functions if you find them necessary. Mark your additions via comments.
template
struct Node{
Node
T data;
};
template
class LinkedList{
public:
LinkedList() : size(0), head(NULL) {}
void add(T data); // Adds to the front of the list
T& getElement(int pos); // Starts counting at 1, rather than 0
int getSize() { return size; }
bool isEmpty() { return size == 0; }
void display();
template
friend ostream& operator<<(ostream& out, const LinkedList
bool operator==(LinkedList
void reverse(); // Implement this function
private:
Node
int size;
};
template
void LinkedList
// Implement this function
}
template
void LinkedList
Node
newNode->data = data;
newNode->next = head;
head = newNode;
size++;
}
template
T& LinkedList
if (pos < 1 || pos > size) throw - 1;
Node
for (int i = 1; i < pos; i++){
curr = curr->next;
}
return curr->data;
}
template
void LinkedList
Node
while (curr != NULL){
cout << curr->data << " -> ";
curr = curr->next;
}
cout << "NULL";
}
template
ostream& operator<<(ostream& out, const LinkedList
Node
while (curr != NULL){
out << curr->data << " -> ";
curr = curr->next;
}
out << "NULL";
return out;
}
template
bool LinkedList
if (size != rhs.size) return false;
Node
Node
while (a != NULL){
if (a->data != b->data) return false;
a = a->next;
b = b->next;
}
return true;
}
int main(){
// Your testing code goes here
return 0;
}
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
