-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreversing_ll.cpp
More file actions
81 lines (63 loc) · 1.6 KB
/
reversing_ll.cpp
File metadata and controls
81 lines (63 loc) · 1.6 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
#include <iostream>
#include <vector>
using namespace std;
class LLNode {
public:
int data;
LLNode *next;
LLNode();
LLNode(int);
void printll();
void appendtoTail(int);
LLNode *reverseList();
};
LLNode::LLNode() : data(0), next(NULL) {}
LLNode::LLNode(int data) : data(data), next(NULL) {}
void LLNode::printll() {
LLNode *currentNode = this;
while (currentNode->next != NULL) {
cout << currentNode->data << "->";
currentNode = currentNode->next;
}
cout << currentNode->data << '\n';
return;
}
void LLNode::appendtoTail(int data) {
LLNode *currentNode = this;
while (currentNode->next != NULL)
currentNode = currentNode->next;
currentNode->next = new LLNode(data);
return;
}
LLNode *LLNode::reverseList() {
LLNode *head = this;
LLNode *current = this;
LLNode *prev = NULL;
LLNode *next = current->next;
while (next != NULL) {
current->next = prev;
prev = current;
current = next;
next = current->next;
}
current->next = prev;
head = current;
return head;
}
LLNode *createLL(vector<int> &vals) {
LLNode *head = new LLNode(vals[0]);
vector<int>::iterator it;
LLNode *currentNode = head;
for (it = vals.begin() + 1; it != vals.end(); it++) {
currentNode->next = new LLNode(*it);
currentNode = currentNode->next;
}
return head;
}
int main([[maybe_unused]] int argc, [[maybe_unused]] char **argv) {
vector<int> vals{1, 2, 3, 4, 5, 6, 7, 8};
LLNode *head = createLL(vals);
head->printll();
head = head->reverseList();
head->printll();
}