c++單鏈表實現大數的求和運算
阿新 • • 發佈:2019-01-02
首先list.h
#ifndef LIST_H #define LIST_H #include <string> #include <iostream> #include <cassert> using namespace std; typedef struct NODE node; typedef struct NODE* nodeptr; typedef string::size_type size_type; struct NODE { nodeptr link; int value; }; class List { private : nodeptr head; nodeptr tail; int charToInt(char ch) { return ((int)ch - 48); } public : List(); void create(string& str); void insertBack(int value); void reverse(); List& operator+(List& list); void show(); }; #endif //建構函式,預設構造一個只有頭結點的連結串列 List :: List() { head = (nodeptr)operator new(sizeof(node)); assert(head != NULL); head -> link = NULL; head -> value = 0; tail = NULL; } //根據傳入的大數字符串建立一個相對應的連結串列 void List :: create(string& str) { for(size_type i = 0; i < str.size(); ++ i) { insertBack(charToInt(str[i])); } } //每次都在連結串列的後面插入 void List :: insertBack(int value) { if(tail == NULL) { head -> value = value; tail = head; return; } nodeptr newNode = (nodeptr)operator new(sizeof(node)); assert(tail != NULL); assert(newNode != NULL); newNode -> link = tail -> link; tail -> link = newNode; newNode -> value = value; tail = newNode; } //用三個指標實現單鏈表的逆序,這是面試真題 void List :: reverse() { nodeptr curr = head; nodeptr pre = NULL; nodeptr next; while(curr != NULL) { next = curr -> link; curr -> link = pre; pre = curr; curr = next; } head = pre; } //過載+運算子 //單鏈表實現大數運算最主要的函式 List& List :: operator+(List& list) { List *list3 = new List(); int bitAdd = 0; int jinWei = 0; this -> reverse(); list.reverse(); nodeptr pList1 = this -> head; nodeptr pList2 = list.head; while(pList1 != NULL || pList2 != NULL) { if(pList1 != NULL && pList2 != NULL) { bitAdd = pList1 -> value + pList2 -> value + jinWei; jinWei = bitAdd / 10; bitAdd = bitAdd % 10; pList1 = pList1 -> link; pList2 = pList2 -> link; } else if(pList1 == NULL) { bitAdd = pList2 -> value; jinWei = 0; pList2 = pList2 -> link; } else { bitAdd = pList1 -> value; jinWei = 0; pList1 = pList1 -> link; } list3 -> insertBack(bitAdd); } if(jinWei != 0) list3 -> insertBack(jinWei); list3 -> reverse(); return *list3; } //螢幕上打印出連結串列 void List :: show() { nodeptr it = head; while(it != NULL) { cout << it -> value; it = it -> link; } cout << endl; }
然後是測試程式
#include "list.h" #include <iostream> using namespace std; int main() { string str1; string str2; cout << "please input the number1: "; cin >> str1; cout << "please input the number2: "; cin >> str2; List bigNum1; List bigNum2; List result; bigNum1.create(str1); bigNum2.create(str2); result = bigNum1 + bigNum2; cout << "result : " << endl; result.show(); return 0; }