Skip to content

Instantly share code, notes, and snippets.

@ealmansi
Last active October 13, 2017 17:29
Show Gist options
  • Save ealmansi/47e0339defcfcee9891917ded4cd4758 to your computer and use it in GitHub Desktop.
Save ealmansi/47e0339defcfcee9891917ded4cd4758 to your computer and use it in GitHub Desktop.
Algorithm to Reverse a Singly-Linked List in C++
#include <iostream>
using namespace std;
struct node;
node * const NIL = (node * const) 0;
struct node {
int value;
node *next;
node(int value) : value(value), next(NIL) {}
node(int value, node *next) : value(value), next(next) {}
~node() { if (next) delete next; }
};
node *reverse(node *n) {
node *h = NIL;
while (n != NIL) {
node *t = n->next;
n->next = h;
h = n;
n = t;
}
return h;
}
void print(node *n) {
cout << "[";
while (n != NIL) {
cout << n->value;
if (n->next != NIL) {
cout << ", ";
}
n = n->next;
}
cout << "]" << endl;
}
int main() {
node *r;
r = reverse(NIL);
print(r); delete r; // []
r = reverse(new node(1));
print(r); delete r; // [1]
r = reverse(new node(1, new node(2)));
print(r); delete r; // [2, 1]
r = reverse(new node(1, new node(2, new node(3))));
print(r); delete r; // [3, 2, 1]
r = reverse(new node(1, new node(2, new node(3, new node(4)))));
print(r); delete r; // [4, 3, 2, 1]
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment