【问题标题】:C++ How to add polynomial using linked listC ++如何使用链表添加多项式
【发布时间】:2017-02-24 05:36:13
【问题描述】:

看一下代码,在添加多项式(列表)时,我在运算符重载中做错了什么?它没有打印所需的答案。 例如

P1:5x^12 + 2x^9 + 4x^7 + 6x^6 + 1x^3

P2:7x^8 + 2x^7 + 8x^6 + 6x^4 + 2x^2 + 3^x + 40

答案:5x^12 + 2x^9 + 7x^8 + 6x^7 + 14x^6 + 6x^4 + 1x^3 + 2x^2 + 3^x + 40

添加它们的正确方法是什么?

#include <stdio.h>
#include <iostream>

using namespace std;

//Node is defined
class node {
public:
    //value will contain data
    int value1;
    int value2;
    //next stores location
    node *next;

    //Default Constructor
    node()
    {
        value1 = 0;
        value2 = 0;
        next = NULL;
    }
};

//mylist is defined
class mylist {
public:

    //head will keep notice of beginning of the list
    node* head;

    //track number of nodes
    int count = 0;

    //default constructor
    mylist() {}

    //constructor


    //insert at beginning
    void insert_at_beginning(int new_value1, int new_value2)
    {
        //creating new node
        node *new_node = new node();

        //increasing count
        count++;

        //copying value to new_node
        new_node->value1 = new_value1;
        new_node->value2 = new_value2;
        //pointing head to new_node when we have empty list
        if (head == NULL)
        {
            head = new_node;
        }
        //when list isn't empty
        else
        {
            /* new_node->next points where heads points*/
            new_node->next = head;

            /* Updating head node to point to newly added node*/
            head = new_node;
        }
    }

    //inert node or item at Specific Location
    void insert_at_loc(int location, double new_val1, double new_val2)
    {
        //temp node to keep track of location
        node* temp = head;

        //x acts as counter
        int x = count;

        //check if location is valid or not
        if (count < location) {
            cout << ("\n --Invalid Location Node Can't be Added at this Location -- ") << endl;
        }
        else {
            //traversing thourgh list finding specific location to add node
            while (x != NULL) {
                if (x == (count - location + 2)) {

                    //found location now creating new node and fixing links
                    node *new_node1 = new node();

                    //increasing count
                    count++;
                    new_node1->value1 = new_val1;
                    new_node1->value2 = new_val2;
                    //new_node1->next points to temp->next
                    new_node1->next = temp->next;

                    //temp-next points to newly added new_node1
                    temp->next = new_node1;
                }
                else {
                    temp = temp->next;
                }
                x--;
            }

        }

    }

    //printing list
    void printList()
    {
        cout << endl << "Linked-List : ";
        node* temp = head;

        while (temp != NULL) {
            cout << temp->value2 << "x^" << temp->value1 << "--> ";
            temp = temp->next;
        }
    }

    void del(int del_loc) {

        //temp1 to keep track location
        node* t1 = head;

        //if location is head 
        if (del_loc <= 1) {
            head = t1->next;

            //free memory
            delete(t1);

            //decrementing count
            count--;
        }
        //location is other than head
        else if (del_loc < count) {
            for (int y = count; y != (count - del_loc + 2); y--) {
                t1 = t1->next;
            }
            //fixing links
            node* t2 = t1->next;
            t1->next = t2->next;

            //free memory
            delete t2;

            //decrementing count
            count--;
        }
        else {
            cout << "\n **Sorry Location Doesn't Exist **" << endl;
        }
    }

    //Display Number of Nodes
    void count_func() {
        cout << "\n\n No. of Nodes Present in Linked List : " << count << endl;
    }

    void mylist::operator+=(const mylist& l2) {
        node *temp_l1 = head;
        node *temp_l2 = l2.head;
        mylist answer;

        while ((temp_l1 != NULL) && (temp_l2 != NULL)) {
            if (temp_l1 != NULL && temp_l2 == NULL) {
                answer.insert_at_beginning(temp_l1->value1, temp_l1->value2);
                temp_l1 = temp_l1->next;
            }

            if (temp_l1 == NULL && temp_l2 != NULL) {
                answer.insert_at_beginning(temp_l2->value1, temp_l2->value2);
                temp_l2 = temp_l2->next;
            }

            if (temp_l1 != NULL && temp_l2 != NULL) {
                if (temp_l1->value1 == temp_l2->value1) {
                    answer.insert_at_beginning(temp_l1->value1, (temp_l1->value2+temp_l2->value2) );
                    if (temp_l1 != NULL)
                        temp_l1 = temp_l1->next;
                    if (temp_l2 != NULL)
                        temp_l2 = temp_l2->next;
                }
                else if (temp_l1->value1 > temp_l2->value1 ) {
                    answer.insert_at_beginning(temp_l1->value1, temp_l1->value2);
                    temp_l1 = temp_l1->next;

                }
                else if (temp_l1->value1 < temp_l2->value1) {
                    answer.insert_at_beginning(temp_l2->value1, temp_l2->value2);
                    temp_l2 = temp_l2->next;

                }
            }
        }
        node *temp_ans = answer.head;
        while (temp_ans != NULL) {
            cout << temp_ans->value2 << "z^" << temp_ans->value1 << "--> ";
            temp_ans = temp_ans->next;
        }

    }
};



int main() {

    //creating linked_list
    mylist linked_list;
    mylist linked_list_1;
    mylist linked_list_2;
    mylist linked_list_ans;
    int menu = 0;

    int list_1_exp = 0;
    int list_1_exp_check = -100;
    double list_1_coef;
    char list_1_menu = 0;

    cout << " *********************** Enter 1st Polynomial in Ascending Order w.r.t Exponential *********************** " << endl;

    while (list_1_menu != 'E' || list_1_menu != 'e') {

        cout << " \nWould you like to add term in 1st Polynomial (y or n): " << endl;
        cout << " Enter 'E' to exit: " << endl;
        cout << " Your Choice: ";
        cin >> list_1_menu;

        if (list_1_menu == 'Y' || list_1_menu == 'y') {

            cout << "Enter the Exponent for the term : ";
            cin >> list_1_exp;

            if (list_1_exp > list_1_exp_check || list_1_exp_check == -100) {
                list_1_exp_check = list_1_exp;
            }
            else if (list_1_exp <= list_1_exp_check) {
                cout << " Invalid Exponent for the term (can't be Equal or Less than Last Term) " << endl;
                cout << " Please Enter Exponent Greater than " << list_1_exp_check << endl;
                cout << " Enter the Exponent for the term : ";
                cin >> list_1_exp;
                list_1_exp_check = list_1_exp;
            }

            cout << "Enter the Coefficent for the term : ";
            cin >> list_1_coef;

            linked_list_1.insert_at_beginning(list_1_exp, list_1_coef);

            linked_list_1.printList();
            cout << " NULL" << endl << endl;
        }
        else if (list_1_menu == 'N' || list_1_menu == 'n') {
            break;
        }
        else if (list_1_menu == 'E' || list_1_menu == 'e') {
            break;
        }
    }

    //priting list
    linked_list_1.printList();
    cout << " NULL" << endl << endl;

    int list_2_exp = 0;
    int list_2_exp_check = -100;
    double list_2_coef;
    char list_2_menu = 0;

    cout << " \n *********************** Enter 2nd Polynomial in Ascending Order w.r.t Exponential ***********************" << endl;

    while (list_2_menu != 'E' || list_2_menu != 'e') {

        cout << " \nWould you like to add term in 2nd Polynomial (y or n): " << endl;
        cout << " Enter 'E' to exit: " << endl;
        cout << " Your Choice: ";
        cin >> list_2_menu;

        if (list_2_menu == 'Y' || list_2_menu == 'y') {

            cout << "Enter the Exponent for the term : ";
            cin >> list_2_exp;

            if (list_2_exp > list_2_exp_check || list_2_exp_check == -100) {
                list_2_exp_check = list_2_exp;
            }
            else if (list_2_exp <= list_1_exp_check) {
                cout << " Invalid Exponent for the term (can't be Equal or Less than Last Term) " << endl;
                cout << " Please Enter Exponent Greater than " << list_2_exp_check << endl;
                cout << " Enter the Exponent for the term : ";
                cin >> list_2_exp;
                list_2_exp_check = list_2_exp;
            }

            cout << "Enter the Coefficent for the term : ";
            cin >> list_2_coef;

            linked_list_2.insert_at_beginning(list_2_exp, list_2_coef);

            linked_list_2.printList();
            cout << " NULL" << endl << endl;
        }
        else if (list_2_menu == 'N' || list_2_menu == 'n') {
            break;
        }
        else if (list_2_menu == 'E' || list_2_menu == 'e') {
            break;
        }
    }

    //priting list
    linked_list_2.printList();
    cout << " NULL" << endl << endl;

    linked_list_1.printList();
    cout << " NULL" << endl << endl;


    cout << " Addition " << endl;

    linked_list_1 += (linked_list_2);


    cout << "\nFinal List" << endl;
    linked_list_ans.printList();


    //program success
    system("pause");
    return 0;

}

我认为我尝试添加的逻辑是有道理的,但它不起作用。在大多数情况下,它的工作原理就像我在多项式中具有相同次数的相等项。它适用于此,但并非适用于所有情况。请帮忙!

【问题讨论】:

  • 严重缺乏封装,以及该设计中的职责混合。实现的operator+= 在名为mylist 的类上几乎没有意义。更合适的方法是有一个类polynomial,它使用一些按组合的链表来表示多项式。除非这是编写您自己的列表的练习,否则重用 std::list 之类的内容可能更合适。 |许多变量和参数的名称相当无意义,这也可以进行一些改进。
  • 是的,同意,应该使用成员函数从类中获取所需的数据,但这只是一个学习任务来解释它们是如何工作的,我遇到的唯一问题是除了多项式输出会删除最后一个条目。请回答这个问题
  • 如果一定要制作链表,先从链表开始。通过单独测试来确保链表功能正常。然后按照@DanMašek 的建议并在多项式类中使用链表。两个原因: 1. 一次测试和调试一件事要容易得多。 2. 帮助你以你想要的方式编写这个程序只会教你成为一个糟糕的程序员。世界上有足够多的糟糕程序员。
  • while ((temp_l1 != NULL) &amp;&amp; (temp_l2 != NULL)) 所以 temp 都不是 NULL。在这种情况下,(temp_l1 != NULL &amp;&amp; temp_l2 == NULL) 将是错误的。 (temp_l1 == NULL &amp;&amp; temp_l2 != NULL) 也将如此,因为没有进行任何更改。而(temp_l1 != NULL &amp;&amp; temp_l2 != NULL) 将永远是正确的。因此,如果我没看错,您可以删除 while 循环的前 11 行,什么都不会改变。在我看来,您将过早停止迭代(一些节点仍留在一个列表中)。绝对考虑重构它,并编写一些单元测试。

标签: c++ linked-list operator-overloading polynomials


【解决方案1】:

为什么不保持简单:

创建一个map&lt;int, int&gt;。遍历P1和P2,将indices插入为key,将coefficient插入为value。如果映射中已经存在indexpower,则增加条目的值,否则创建索引为key 的新条目。遍历完 P1 和 P2 后,map 将由 index 为 key 的 entry 组成,P1 和 P2 中每个 power/index 的系数之和为对应的 value。

【讨论】:

  • 是的,我知道这存在。但我需要制作自己的清单,以了解基本的流程正在发生的事情。
【解决方案2】:

循环条件(temp_l1 != NULL) &amp;&amp; (temp_l2 != NULL)保证temp_l1 != NULL &amp;&amp; temp_l2 == NULLtemp_l1 == NULL &amp;&amp; temp_l2 != NULL始终为假,因此对应的ifs的主体永远不会被执行。将它们从循环中取出(当然也将它们转换为循环)。

PS:要快速发现此类问题,请使用调试器。

【讨论】:

  • 最后,感谢您理解问题并指出错误,您的回答正好解决了问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-12
相关资源
最近更新 更多