-
Notifications
You must be signed in to change notification settings - Fork 0
/
rev_ll.cpp
58 lines (49 loc) · 877 Bytes
/
rev_ll.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
/*
* rev_ll.cpp
*
* Created on: Jun 12, 2014
* Author: jlin
*/
#include <iostream>
using namespace std;
class Node {
public:
int data;
Node *next;
Node(int i) : data(i), next(NULL) {}
};
void reverse_iterative(Node **head) {
if (!*head) return;
Node *cur = *head;
Node *next = cur->next;
(*head)->next = NULL;
while (next) {
Node *nextnext = next->next;
next->next = cur;
cur = next;
next = nextnext;
}
}
void reverse_iterative2(Node **head) {
if (!*head) return;
Node *prev = NULL;
Node *curr = *head;
while (curr) {
Node *next = curr->next;
curr->next = prev;
prev = curr;
curr = next;
}
*head = prev;
}
void reverse_recursive(Node **head) {
if (!*head) return;
Node *rest = (*head)->next;
if (!rest) return;
reverse_recursive(&rest);
(*head)->next->next = *head;
(*head)->next = NULL;
*head = rest;
}
int main() {
}