/
reverseList.cpp
80 lines (74 loc) · 1.29 KB
/
reverseList.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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
#include<iostream>
class Node{
public:
Node(){
this->value = 0;
this->next = NULL;
}
Node(int v){
this->value = v;
this->next = NULL;
}
void setNext(Node *next){
this->next = next;
}
int getValue(){
return this->value;
}
Node* getNext(){
return this->next;
}
private:
Node *next;
int value;
};
class List{
public:
List(){
this->root = new Node();
this->last = this->root;
}
void printList(){
Node *head = this->root->getNext();
while(head){
std::cout << head->getValue() << std::endl;
head = head->getNext();
}
}
void addNode(int v){
Node *newNode = new Node(v);
this->last->setNext(newNode);
this->last = last->getNext();
}
Node* getMidNode(){
Node *head = root->getNext();
Node *back = head;
while(back && back->getNext() && (back->getNext())->getNext()){
head = head->getNext();
back = (back->getNext())->getNext();
}
return head;
}
~List(){
Node *head = this->root;
while(head){
Node *tmp = head->getNext();
delete head;
head = tmp;
}
}
private:
Node *root;
Node *last;
};
int main(){
List test;
for(int i = 1; i < 11; i++){
test.addNode(i);
}
test.printList();
Node *tmp;
tmp = test.getMidNode();
std::cout << tmp->getValue() << std::endl;
return 0;
}