fueanta

Sorting while inserting nodes in linked list

Dec 4th, 2016
121
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // Sorting while inserting nodes in linked list
  2.  
  3. #include <iostream>
  4. using namespace std;
  5.  
  6. typedef struct List {
  7.     int key;
  8.     struct List *next;
  9. } nodeType, *nodePtr;
  10.  
  11. nodePtr createList(nodePtr node) {
  12.     cout << "\nHow many elements do wish to have in your list? Elements: ";
  13.     int els; cin >> els; nodePtr curr = NULL;
  14.     for (int i = 0; i < els; i++) {
  15.         cout << "\nElement " << i + 1 << ": ";
  16.         int item; cin >> item;
  17.         nodePtr newNODE = new nodeType;
  18.         newNODE->key = item; newNODE->next = NULL;
  19.         if (node == NULL)
  20.             node = newNODE;
  21.         else if (node->key > item) {
  22.             newNODE->next = node;
  23.             node = newNODE;
  24.         }
  25.         else {
  26.             curr = node;
  27.             while (curr->next != NULL && curr->next->key < item)
  28.                 curr = curr->next;
  29.             if (curr->next == NULL)
  30.                 curr->next = newNODE;
  31.             else {
  32.                 newNODE->next = curr->next;
  33.                 curr->next = newNODE;
  34.             }
  35.         }
  36.     }
  37.     return node;
  38. }
  39.  
  40. void dispList(nodePtr node) {
  41.     cout << "\n\nThe list so far: ";
  42.     while (node != NULL) {
  43.         cout << node->key << " ";
  44.         node = node->next;
  45.     }
  46. }
  47.  
  48. int main() {
  49.     nodePtr start = NULL;
  50.     start = createList(start);
  51.     dispList(start);
  52.     cout << "\n\n";
  53.     return 0;
  54. }
RAW Paste Data