Skip to content

Instantly share code, notes, and snippets.

@ICyperior
Last active September 3, 2022 19:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ICyperior/e48114d073e53754a734285d572f1609 to your computer and use it in GitHub Desktop.
Save ICyperior/e48114d073e53754a734285d572f1609 to your computer and use it in GitHub Desktop.
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