Advertisement
vencinachev

Hw2-Bobi

Feb 5th, 2021
1,084
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.73 KB | None | 0 0
  1. // Упражнение 6: Задачa 4
  2. #include <iostream>
  3. #include <cmath>
  4. #define EPSILON 0.000001
  5.  
  6. using namespace std;
  7.  
  8. struct Item {
  9.     double info;
  10.     Item *next;
  11. };
  12.  
  13. bool areEquals(double a, double b) {
  14.    return fabs(a - b) < EPSILON;
  15. }
  16.  
  17. Item* Create(Item* Head){
  18.     Item* Last=NULL, *P;
  19.     char ch;
  20.     cout << " enter new element (Y/N) ?:";
  21.     cin >> ch;
  22.     while (ch == 'Y' || ch == 'y') {
  23.         P = new Item;
  24.         cout << " enter integer value of new element : ";
  25.         cin >> P->info;
  26.         P->next = NULL;
  27.         if (Head == NULL) Head = P;
  28.         else Last->next = P;
  29.         Last = P;
  30.         cout << " enter new element (Y/N) ?:";
  31.         cin >> ch;
  32.     }
  33.     return Head;
  34. }
  35.  
  36.  
  37. void Traverse(Item* P) {
  38.     while (P != NULL) { //или while (P) {
  39.         cout << "next el:" << P->info << "\n";
  40.         P = P->next;
  41.     }
  42. }
  43.  
  44. Item* Search(double X, Item* P) {
  45.     while (P != NULL && !areEquals(P->info, X)){
  46.         P = P->next;
  47.     }
  48.     return P;
  49. }
  50.  
  51. int ListSize(Item* P){
  52.     int cnt = 0;
  53.     while (P != NULL){
  54.         P = P->next;
  55.         cnt++;
  56.     }
  57.     return cnt;
  58. }
  59.  
  60. int SearchPos(double X, Item* P) {
  61.     int pos = 0;
  62.     while (P != NULL && !areEquals(P->info, X)){
  63.         P = P->next;
  64.         pos++;
  65.     }
  66.     return pos;
  67. }
  68.  
  69. int main() {
  70.     Item* Head = NULL;
  71.     Head = Create(Head);
  72.     Traverse(Head);
  73.  
  74.     double num;
  75.     cout << "Enter element for searching: ";
  76.     cin >> num;
  77.     Item* El = Search(num, Head);
  78.     if (El != NULL){
  79.         cout << "Found. Position: " << SearchPos(num, Head) << endl;
  80.     } else {
  81.         cout << "Not found" << endl;
  82.     }
  83.  
  84.     cout << "List size: " << ListSize(Head) << endl;
  85.  
  86.     return 0;
  87. }
  88.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement