-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreverse_block.cpp
More file actions
90 lines (83 loc) · 1.83 KB
/
Copy pathreverse_block.cpp
File metadata and controls
90 lines (83 loc) · 1.83 KB
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
/******************************************************************************
* Compilation: g++ -o reverse_block.cpp -std=c++0x -g
* Execution: ./a.out [n]
* Dependencies:
*
* block reverse in list
* % ./a.out 3
* abcdefghijk
* c
* b
* a
* f
* e
* d
* j
* i
* h
* k
*
******************************************************************************/
#include <cstdlib>
#include <iostream>
#include <string>
using std::string;
template <typename T>
class Node {
public:
T item;
Node* next;
Node() : item(T()), next(NULL) {}
};
template <typename T>
void print_node_list(Node<T>* x) {
while (x != NULL) {
std::cout << x->item << std::endl;
x = x->next;
}
}
template <typename T>
Node<T>* block_reverse(Node<T>* first, int k) {
Node<T>* current = first;
Node<T>* prev = NULL;
int count = 0;
while (count < k && current != NULL) {
Node<T>* next = current->next;
current->next = prev;
prev = current;
current = next;
count++;
}
if (current != NULL)
first->next = block_reverse(current, k);
return prev;
}
public Node reverse(Node first) {
if (first == null) return null;
if (first.next == null) return first;
Node second = first.next;
Node rest = reverse(second);
second.next = first;
first.next = null;
return rest;
}
int main(int argc, char* argv[]) {
if (argc < 2) {
std::cout << "arguments to main is insufficient!" << std::endl;
return -1;
}
int block_size = std::atoi(argv[1]);
string s;
std::getline(std::cin, s);
Node<char>* prev = new Node<char>();
prev->item = s[0];
Node<char>* first = prev;
for (int i = 1; i < s.length(); i++) {
Node<char>* current = new Node<char>();
current->item = s[i];
prev->next = current;
prev = current;
}
first = block_reverse(first, block_size);
print_node_list(first);
}