-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathlinked_list.cpp
More file actions
67 lines (56 loc) · 1.48 KB
/
linked_list.cpp
File metadata and controls
67 lines (56 loc) · 1.48 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
//
// Created by Mayank Parasar on 2019-12-02.
//
#include <iostream>
using namespace std;
struct node {
int value;
node* next;
node(int val, node* ptr= nullptr)
: value(val), next(ptr)
{};
void add_elem_last(node* list, node* elem) {
int size_of_list = 0;
// traverse the linked-list till the end
// then add this ptr at the end
while (list->next != nullptr) {
list = list->next;
size_of_list++;
}
list->next = elem;
elem->next = nullptr;
cout << " size of the list is: " << ++size_of_list << endl;
return;
}
// declare
void print_list(node* );
};
ostream & operator << (ostream &out, node* n1) {
out << n1->value << endl;
// cout << *(n1->next);
if (n1->next == nullptr)
out << "This node is the last node in link-list" << endl;
else
out << "This node points to next node, with value: " \
<< n1->next->value << endl;
return out;
}
void node::print_list(node* list) {
while (list->next != nullptr) {
cout << list << endl;
list = list->next;
}
cout << list << endl;
}
int main(int argc, char const *argv[]) {
/* code */
node a(1, nullptr);
cout << a.value << endl;
node* b = new node(2, &a); // b is the head of this list
cout << b << endl;
node* c = new node(3);
b->add_elem_last(b, c);
// print the link list in nice format
b->print_list(b);
return 0;
}