Advertisement
nhbao

Untitled

Apr 9th, 2020
196
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.32 KB | None | 0 0
  1. #include <iostream>
  2. using namespace std;
  3. struct node
  4. {
  5.     int data;
  6.     struct node* pNext;
  7. };
  8. typedef struct node NODE;
  9. struct list
  10. {
  11.     NODE* pHead;
  12.     NODE* pTail;
  13. };
  14. typedef struct list LIST;
  15. void init(list& a)
  16. {
  17.     a.pHead = NULL;
  18.     a.pTail = NULL;
  19. }
  20. NODE* getNode(int x)
  21. {
  22.     NODE* p = new NODE;
  23.     p->pNext = NULL;
  24.     p->data = x;
  25.     return p;
  26. }
  27. void addNotetoHead(list& a, NODE* b)
  28. {
  29.     if (a.pHead == NULL)
  30.     {
  31.         a.pHead = b = a.pTail;
  32.     }
  33.     else
  34.     {
  35.  
  36.         b->pNext = a.pHead;
  37.         a.pHead = b;
  38.     }
  39.  
  40. }
  41. void addNotetoTail(list& a, NODE* b)
  42. {
  43.     if (a.pHead == NULL)
  44.     {
  45.         a.pHead = b = a.pTail;
  46.     }
  47.     else
  48.     {
  49.  
  50.         a.pTail->pNext = b;
  51.         a.pTail = b;
  52.     }
  53.  
  54. }
  55. void input(list& a)
  56. {
  57.     int x;
  58.     cout << "nhap so luong phan tu x:";
  59.     cin >> x;
  60.     for (int i = 1; i <= x; i++)
  61.     {
  62.         int n;
  63.         cout << "nhap gia tri can truyen vao:";
  64.         cin >> n;
  65.         NODE* p = getNode(n);
  66.         addNotetoHead(a, p);
  67.     }
  68. }
  69. void output(list a)
  70. {
  71.     for (NODE* p = a.pHead; p != NULL; p = p->pNext)
  72.     {
  73.         cout << p->data << " ";
  74.     }
  75. }
  76. int Sum(list a)
  77. {
  78.     int tong = 0;
  79.     for (NODE* p = a.pHead; p != NULL; p = p->pNext)
  80.     {
  81.         tong = tong + p->data;
  82.     }
  83.     return tong;
  84. }
  85. int main()
  86. {
  87.     LIST l;
  88.     init(l);
  89.     input(l);
  90.     cout << "danh sach LKD: \n";
  91.     output(l);
  92.     int kq = Sum(l);
  93.     cout << "tong cac gia tri :\n" << kq;
  94.     system("pause");
  95.     return 0;
  96. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement