Advertisement
huutho_96

Cộng Đa Thức

Jun 11th, 2015
440
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.39 KB | None | 0 0
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. struct Node
  5. {
  6.     int heso, somu;
  7.     Node *pNext;
  8. };
  9. struct List
  10. {
  11.     Node *pHead, *pTail;
  12. };
  13.  
  14. void AddHead(List &L, Node *p)
  15. {
  16.     if (L.pHead == NULL)
  17.     {
  18.         L.pHead = L.pTail = p;
  19.     }
  20.     else
  21.     {
  22.         p->pNext = L.pHead;
  23.         L.pHead = p;
  24.     }
  25. }
  26.  
  27. void CreateList(List &L)
  28. {
  29.     L.pHead = L.pTail = NULL;
  30. }
  31.  
  32. Node * CreateNode(int heso, int somu)
  33. {
  34.     Node *p = new Node;
  35.     if (!p) exit(1);
  36.     p->heso = heso;
  37.     p->somu = somu;
  38.     p->pNext = NULL;
  39.     return p;
  40. }
  41.  
  42. void NhapDaThuc(List &L)
  43. {
  44.     int x, y;
  45.     int n;
  46.     cout << "bac cua da thuc: ";
  47.     cin >> n;
  48.     do
  49.     {
  50.         cout << "he so: ";
  51.         cin >> x;
  52.         cout << "so mu: ";
  53.         cin >> y;
  54.         AddHead(L, CreateNode(x, y));
  55.         n--;
  56.     } while (n >= 0);
  57. }
  58.  
  59. void AddDaThuc(List &L, Node *pAdd)
  60. {
  61.     Node *p = L.pHead;
  62.     while (p != NULL && p->somu != pAdd->somu)
  63.         p = p->pNext;
  64.     if (p == NULL) AddHead(L, pAdd);
  65.     else
  66.     {
  67.         p->heso += pAdd->heso;
  68.         delete pAdd;
  69.     }
  70. }
  71.  
  72. void CongDaThuc(List &L, List &L1)
  73. {
  74.     Node *p = NULL;
  75.     while (L1.pHead != NULL)
  76.     {
  77.         p = L1.pHead;
  78.         L1.pHead = p->pNext;
  79.         p->pNext = NULL;
  80.         AddDaThuc(L, p);
  81.     }
  82. }
  83. void Output(List L)
  84. {
  85.     Node *p = L.pHead;
  86.     while (p)
  87.     {
  88.         cout << p->heso << " * x ^ " << p->somu << " + ";
  89.         p = p->pNext;
  90.     }
  91. }
  92. void main()
  93. {
  94.     List L1, L2;
  95.     CreateList(L1);
  96.     CreateList(L2);
  97.     NhapDaThuc(L1);
  98.     NhapDaThuc(L2);
  99.     CongDaThuc(L1, L2);
  100.     Output(L1);
  101. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement