pgrm_026.cpp
Problem Statement
pgrm_026.cpp
WAP to implement a singly linked list with insertion at the beginning and end
Source Code
cpp
#include <iostream>
using namespace std;
class Node {
public:
int info;
Node *next;
Node(int val) {
info = val;
next = NULL;
}
};
class SinglyList {
private:
Node *head;
public:
SinglyList() {
head = NULL;
}
void insertBegin(int val) {
Node *ptr = new Node(val);
ptr->next = head;
head = ptr;
cout << "Inserted " << val << " at the beggining";
}
void insertEnd(int val) {
Node *ptr = new Node(val);
if (head == NULL) {
head = ptr;
} else {
Node *t = head;
while (t->next != NULL) {
t = t->next;
}
t->next = ptr;
}
cout << endl << "Inserted " << val << " at the end";
}
void display() {
Node *t = head; cout << endl << "The list: ";
while(t != NULL) {
cout << t -> info << " ";
t = t -> next;
}
}
};
int main() {
SinglyList obj;
obj.insertBegin(10);
obj.insertBegin(20);
obj.display();
obj.insertEnd(40);
obj.insertEnd(50);
obj.display();
return 0;
}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
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