Question
(In C++ please) How would I maintain the singly linked list in sorted order? Assume that a singly linked list is implemented with a header
(In C++ please)
How would I maintain the singly linked list in sorted order?
Assume that a singly linked list is implemented with a header node, but no tail node, and that it maintains only a pointer to the header node. Write a class that includes methods to:
a. return the size of the linked list
b. print the linked list
c. test if a value x is contained in the linked list
d. add a value x if it is not already contained in the linked list
e. remove a value x if it is contained in the linked list
what I have so far:
#include
using namespace std;
//struct for node of list
struct Node {
int data;
struct Node *next;
};
class SLinkedList {
private:
Node * head = nullptr;
public:
int size();
void print();
bool isPresent(int data);
void add(int data);
void remove(int data);
};
int SLinkedList::size() {
Node *temp = head;
int count = 0;
while (temp) {
++count;
temp = temp->next;
}
return count;
}
void SLinkedList::print() {
Node *temp = head;
cout << "Element of linked list: ";
while (temp) {
cout << temp->data << " ";
temp = temp->next;
}
cout << " ";
}
bool SLinkedList::isPresent(int data) {
Node *temp = head;
while (temp) {
if (temp->data == data) {
return true;
}
temp = temp->next;
}
return false;
}
void SLinkedList::add(int data) {
Node *temp = new Node;
temp->data = data;
temp->next = head;
head = temp;
}
void SLinkedList::remove(int data) {
Node *temp1 = head;
Node *temp2 = temp1;
if (head->data == data) {
head = head->next;
delete temp1;
}
else {
while (temp1->data != data || temp1 != nullptr) {
temp2 = temp1;
temp1 = temp1->next;
}
if (!temp1) {
temp2->next = temp1->next;
delete temp1;
}
}
}
int main() {
SLinkedList list;
for (int i = 0; i < 10; ++i) {
list.add(i);
}
cout << "Size of linked list: " << list.size() << " ";
list.print();
if (list.isPresent(9)) {
cout << "9 is present in list. ";
}
else {
cout << "9 is not present in list. ";
}
list.remove(9);
cout << "List after deleting 9: ";
list.print();
cout << "New size of linked list: " << list.size() << " ";
system("PAUSE");
return 0;
}
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started