Advertisement
vencinachev

Hw1-Bobi

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