Skip to content

Instantly share code, notes, and snippets.

@thewickedaxe
Created October 11, 2016 02:08
Show Gist options
  • Select an option

  • Save thewickedaxe/8a4c7a385a87114fa495dec40a8d4135 to your computer and use it in GitHub Desktop.

Select an option

Save thewickedaxe/8a4c7a385a87114fa495dec40a8d4135 to your computer and use it in GitHub Desktop.
Reversing a linked list with 1 pointer
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cmath>
using namespace std;
struct node {
int key;
node* next;
node (int k) {
key = k;
next = NULL;
}
};
bool rev_head_flag = true;
node* head = NULL;
node* head2;
void insert(int val) {
node* n = new node(val);
if (!head) {
head = n;
return;
} else {
node* temp = head;
while (temp->next != NULL) {
temp = temp -> next;
}
temp -> next = n;
}
}
node*& rev(node*& p) {
if (p -> next) {
rev(p -> next)-> next = p;
}
if (rev_head_flag) {
head2 = p;
rev_head_flag = false;
}
return p;
}
void print_list() {
node* temp = head;
while (temp != NULL) {
cout << "Data: "<<temp -> key << endl;
temp = temp -> next;
}
}
void print_list2() {
node* temp = head2;
while (temp != NULL) {
cout << "Data: "<<temp -> key << endl;
temp = temp -> next;
}
}
int main() {
insert(5);
insert(6);
insert(7);
print_list();
rev(head);
head -> next = NULL;
print_list2();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment