將兩個數字(以連結串列形式表示)相乘,形成第三個連結串列,C++ 實現


有兩個連結串列,其中包含數字。我們需要用兩個連結串列形成的數字相乘。這可以透過從兩個連結串列中形成數字來輕鬆實現。我們來看一個例子。

輸入

1 -> 2 -> NULL
2 -> 3 -> NULL

輸出

2 -> 7 -> 6 -> NULL

演算法

  • 初始化兩個連結串列。
  • 用 0 初始化兩個變數來儲存這兩個數字。
  • 迭代兩個連結串列。
    • 將每個數字新增到末尾的對應數字變數中。
  • 將結果數字相乘並將結果儲存在變數中。
  • 用結果建立一個新連結串列。
  • 列印新連結串列。

實現

以下是上述演算法在 C++ 中的實現

#include <bits/stdc++.h>
using namespace std;
struct Node {
   int data;
   struct Node* next;
};
void addNewNode(struct Node** head, int new_data) {
   struct Node* newNode = new Node;
   newNode->data = new_data;
   newNode->next = *head;
   *head = newNode;
}
void multiplyTwoLinkedLists(struct Node* firstHead, struct Node* secondHead
, struct Node** newLinkedListHead) {
   int _1 = 0, _2 = 0;
   while (firstHead || secondHead) {
      if (firstHead) {
         _1 = _1 * 10 + firstHead->data;
         firstHead = firstHead->next;
      }
      if (secondHead) {
         _2 = _2 * 10 + secondHead->data;
         secondHead = secondHead->next;
      }
   }
   int result = _1 * _2;
   while (result) {
      addNewNode(newLinkedListHead, result % 10);
      result /= 10;
   }
}
void printLinkedList(struct Node *node) {
   while(node != NULL) {
      cout << node->data << "->";
      node = node->next;
   }
   cout << "NULL" << endl;
}
int main(void) {
   struct Node* firstHead = NULL;
   struct Node* secondHead = NULL;
addNewNode(&firstHead, 1);
   addNewNode(&firstHead, 2);
   addNewNode(&firstHead, 3);
   printLinkedList(firstHead);
   addNewNode(&secondHead, 1);
   addNewNode(&secondHead, 2);
   printLinkedList(secondHead);
   struct Node* newLinkedListHead = NULL;
   multiplyTwoLinkedLists(firstHead, secondHead, &newLinkedListHead);
   printLinkedList(newLinkedListHead);
   return 0;
}

輸出

如果執行上面的程式碼,你將會得到以下結果。

3->2->1->NULL
2->1->NULL
6->7->4->1->NULL

更新於: 2021 年 10 月 25 日

201 次瀏覽

開啟你的 職業生涯

完成本課程獲得認證

開始
廣告
© . All rights reserved.