Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <cstdlib>
- #include <memory>
- using namespace std;
- /* Link list node */
- class Node
- {
- public:
- int key;
- Node* next;
- };
- class NodeUtils
- {
- public:
- void push(Node** head_ref, int new_key)
- {
- /* allocate node */
- Node* new_node = new Node();
- /* put in the key */
- new_node->key = new_key;
- /* link the old list off the new node */
- new_node->next = (*head_ref);
- /* move the head to point to the new node */
- (*head_ref) = new_node;
- }
- void listall(Node* head)
- {
- Node* current = head;
- while(current != nullptr) {
- cout << current->key;
- current = current->next;
- if(current) cout << ", ";
- }
- cout << endl;
- }
- /* searches for the value x in linked list */
- bool search(Node* head, int x)
- {
- Node* current = head;
- while(current != nullptr) {
- if (current->key == x)
- return true;
- current = current->next;
- }
- return false;
- }
- unsigned count(Node* head)
- {
- Node* current = head;
- unsigned count = 0;
- while(current != nullptr) {
- current = current->next;
- count++;
- }
- return count;
- }
- void
- sortasc(Node* head)
- {
- Node* temphead = head;
- int tempkey;
- unsigned counter = count(head);
- for(unsigned n = 0; n < counter; n++) {
- while(temphead->next) {
- if(temphead->key > temphead->next->key) {
- tempkey = temphead->key;
- temphead->key = temphead->next->key;
- temphead->next->key = tempkey;
- }
- temphead = temphead->next;
- }
- temphead = head;
- }
- }
- void sortdsc(Node* head)
- {
- Node* temphead = head;
- int tempkey;
- unsigned counter = count(head);
- for(unsigned n = 0; n < counter; n++) {
- while(temphead->next) {
- if(temphead->key < temphead->next->key) {
- tempkey = temphead->key;
- temphead->key = temphead->next->key;
- temphead->next->key = tempkey;
- }
- temphead = temphead->next;
- }
- temphead = head;
- }
- }
- };
- int
- main(int argc, char** argv)
- {
- /* Start with the empty list */
- unique_ptr<NodeUtils> utl = make_unique<NodeUtils>();
- Node* head = nullptr;
- utl->push(&head, 10);
- utl->push(&head, 30);
- utl->push(&head, 11);
- utl->push(&head, 21);
- utl->push(&head, 14);
- utl->search(head, 21)? cout << "Node found" << endl :
- cout << "Node not found" << endl;
- utl->listall(head);
- cout << "number of elements: " << utl->count(head) << endl;
- utl->sortasc(head);
- cout << "Sorted ascending:" << endl;
- utl->listall(head);
- utl->sortdsc(head);
- cout << "Sorted descending:" << endl;
- utl->sortdsc(head);
- utl->listall(head);
- return EXIT_SUCCESS;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement