#include <iostream>
using namespace std;
class LinkedList
{
private:
struct node
{
float val;
node* link;
};
node *first, *last, *newnode;
int node_count{ 0 };
public:
LinkedList()
{
first = nullptr;
last = nullptr;
}
void addNode(float val)
{
newnode = new node;
newnode->val = val;
newnode->link = nullptr;
if (first == nullptr) {
first = newnode;
last = newnode;
}
else {
last->link = newnode;
last = newnode;
}
node_count++;
}
void printList()
{
node* current;
current = first;
while (current != nullptr)
{
cout << current->val << " ";
current = current->link;
}
cout << endl;
}
void sortList()
{
node *current, *bcurrent;
current = first;
bcurrent = first->link;
for (int i = node_count - 1; i >= 0; i--)
{
current = first;
bcurrent = first->link;
for (int j = 0; j < node_count - 1; j++) {
if (current->val > bcurrent->val) {
swap(current->val, bcurrent->val);
}
current = bcurrent;
bcurrent = bcurrent->link;
}
}
}
};
int main()
{
LinkedList s;
int n;
double val;
cout << "Enter the number of items in the list ";
cin >> n;
for (int i = 0; i < n; i++)
{
cout << "Enter the " << i + 1 << " element in the list ";
cin >> val;
s.addNode(val);
}
cout << "Initial list: ";
s.printList();
s.sortList();
cout << "Sorted list: ";
s.printList();
return 0;
}
Comments
Leave a comment