-
Notifications
You must be signed in to change notification settings - Fork 0
/
list.cpp
123 lines (90 loc) · 2.61 KB
/
list.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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
/**
@author [mst]
@file list.cpp
@brief Linked list implementations
[bp] there are different approaches to linked list implementations. A "value
and pointer" node with a push function will suffice for quick tasks. A
higher level "list" structure may be added to encapsulate additional
functionality, tail pointers, prints, reverse methods.
[wip] add reversall, deletion etc. functionality, vector to lisr etc.
features, changelog:
-2023.01: -some more helper functionality
-2021.04: -initial draft
@author [mst]
@version 0.1 2022.04
*/
#include "list.hpp"
#include <iostream> // usage of console prints
////////////////// DECL_IMPL
void ListNode::printList() {
if (this == nullptr) {
std::cout << "empty list" << std::endl;
return;
}
ListNode* lp = this;
while (lp) {
std::cout << lp->val << "->";
lp = lp->next;
}
std::cout << "nullptr" << '\n';
}
// [demo] externally define a class method
ListNode::ListNode(int x, ListNode *next):
val(x), next(next) {}
// list push helper function
void pushList(ListNode* &head, int val) {
// [bp] this will still work with an empty list case
ListNode* NewNode = new ListNode(val, head);
head = NewNode;
}
// list end insertion helper function
void addTailList(ListNode* &head, int val) {
//if (head == nulptr) { // [demo] unnecessary check
// return
//}
ListNode* NewNode = new ListNode(val, nullptr);
if (head == nullptr) {
head = NewNode;
return;
}
ListNode* ptr = head;
while (ptr->next) {
ptr = ptr->next;
}
ptr->next = NewNode;
}
// iterative list reversal
// used in: leetcode 206
ListNode* reverseList(ListNode* head) {
ListNode* prev = nullptr;
if (head) {
ListNode* curr = head;
ListNode* next;
while (curr){
next = curr->next; // prep forward
curr->next = prev; // link back
prev = curr; // relocate new head
curr = next; // advance
}
}
return prev;
}
////////////////// DRIVER
int main()
{
// [bp] putting this in the global space is an overhead
// even worse in a header file as would foce including in all users
using namespace std;
// [bp] using endl would force a flush.
cout << "[mst] cpp linked listss doodle" << '\n' << '\n';
ListNode* l5 = nullptr;
addTailList (l5,9);
addTailList (l5,9);
addTailList (l5,9);
pushList (l5,8);
addTailList (l5,9);
addTailList (l5,9);
addTailList (l5,9);
l5->printList();
return 0;
}