Answer to Question #236410 in C++ for Rehan

Question #236410
Create a function to sort a unsorted singly linked list.
Note:
1)no global declarations are allowed
2) make class
1
Expert's answer
2021-09-12T18:47:42-0400
#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;
	}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS