Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Reverse a linked list.
#include <iostream>
#include <vector>
class Node {
public:
int data;
Node* next;
Node(int data) {
this->data = data;
next = NULL;
}
};
void reverseLinkedListV1(Node*& head) {
Node* temp = head;
std::vector<Node*> addresses;
do {
addresses.push_back(&(*temp));
} while ((temp = temp->next) != NULL);
head = temp = *(&addresses[addresses.size() - 1]);
for (int i = addresses.size() - 2; i >= 0; i--)
temp = temp->next = *(&addresses[i]);
temp->next = NULL;
}
void printLinkedList(Node* head) {
if (head == NULL)
return;
Node* temp = head;
do {
std::cout << temp->data << " ";//std::endl;
// temp = temp->next;
} while ((temp = temp->next) != NULL);
std::cout << std::endl;
}
int main(int argc, char const* argv[])
{
Node* list;
list = new Node(0);
list->next = new Node(1);
list->next->next = new Node(2);
list->next->next->next = new Node(3);
list->next->next->next->next = new Node(4);
list->next->next->next->next->next = new Node(5);
list->next->next->next->next->next->next = new Node(6);
list->next->next->next->next->next->next->next = new Node(7);
list->next->next->next->next->next->next->next->next = new Node(8);
list->next->next->next->next->next->next->next->next->next = new Node(9);
printLinkedList(list);
reverseLinkedListV1(list);
printLinkedList(list);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment