Repository navigation
Expand file tree
/
Copy path19.cpp
More file actions
63 lines (54 loc) · 1.4 KB
/
Copy path19.cpp
File metadata and controls
63 lines (54 loc) · 1.4 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
#include <iostream>
using namespace std;
class Linkedlist {
private:
struct Node { //creation
int data;
Node *next;
} *start = nullptr;
public:
// Insert at beginning
void insert_beg(int item) {
Node* new_node = new Node;
new_node->data = item;
new_node->next = start;
start = new_node;
}
// Insert at end
void insert_end(int item) {
Node* new_node = new Node;
new_node->data = item;
new_node->next = nullptr;
// If the list is empty, make the new node the start
if (start == nullptr) {
start = new_node;
} else {
Node* temp = start;
// Traverse to the last node
while (temp->next != nullptr) {
temp = temp->next;
}
// Attach new_node at the end
temp->next = new_node;
}
}
// Display function to test the list
void display() {
Node* temp = start;
cout<<"[";
while (temp != nullptr) {
cout << temp->data << " ";
temp = temp->next;
}
cout<<"]\n";
}
};
int main() {
Linkedlist list;
list.insert_end(10);
list.insert_end(20);
list.insert_beg(5);
cout << "Linked List:\n";
list.display();
return 0;
}