【问题标题】:Summing two linked lists where each node is a digit将两个链表相加,其中每个节点都是一个数字
【发布时间】:2012-11-01 23:40:19
【问题描述】:

我正在尝试编写一个对整数求和的函数,每个整数都由一个链表表示,其中每个节点->数据是一个数字 0-9。最低有效位在列表的开头,最高位在末尾。

这是来自《破解编码面试》一书。这是我的代码:

SinglyLinked<int>& addLists(SinglyLinked<int>& ll1, SinglyLinked<int>& ll2)
{
  SinglyLinked<int> *sumList = new SinglyLinked<int>;

  ListNode<int> *node1 = ll1.head; ListNode<int> *node2 = ll2.head;

  int sum, carry = 0;
  while(node1 || node2)
  {
    if(node1)
      sum += node1->data;
    if(node2)
      sum += node2->data;
    sum += carry;

    carry = 0;
    sumList->insertAtEnd(sum%10);
    if(sum > 9)
      carry = 1;
    sum = 0;
    node1 =  node1->next; node2 = node2->next;
  }
  return *sumList;
}

首先,这段代码是否正确?它似乎有效,但是当给定两个不同长度的链表(整数)时,它会出现故障。我想知道这个问题是否只是为了解决整数长度相同的情况。如果不是,我将如何将两个不同长度的列表相加?我天真的解决方案是存储每个列表的长度,然后使用它来创建只有一个数字会贡献的数字,直到两个整数对齐。还有比这更优雅的吗?

【问题讨论】:

    标签: c++ linked-list


    【解决方案1】:

    它在不同长度的列表上出现段错误,因为 node1node2 指向 null。

    改变

    node1 = node1->下一个; node2 = node2->下一个;

    if (node1)
        node1 = node1->next;
    
    if (node2)
        node2 = node2->next;
    

    【讨论】:

    • 不应该是 if(node1->next) 和 if(node2->next) 吗??
    • @ordinary 否,因为node1node2 已经指向null,然后访问node-&gt;next 无效。
    【解决方案2】:
    while(node1 || node2)
    

    如果任一节点都正常,请继续。但是该块希望两个节点在它到达这里时都是有效的:

    node1 =  node1->next; node2 = node2->next;
    

    您需要在 if node1 检查中使用“下一步”:

    if(node1) {
      sum += node1->data;
      node1 = node1->next;
    }
    

    等等

    【讨论】:

      【解决方案3】:

      有一个条件,node1 和 node2 将指向 NULL,如果前一个数字操作有进位,则不会附加到 sumlist 的末尾。例如,6->5->4 + 4->5->6 应该是 0->1->1->1 但 sumlist 将是 0->1->1。所以在返回线之前你应该添加:

      if (carry)
         sumList->insertAtEnd(carry);
      

      【讨论】:

        【解决方案4】:

        这个问题的另一种解决方案是,当您将每个列表中的数字相加,将它们加在一起以获得等于两个列表之和的大和,将该和转换为字符串,并将字符串的每个字符附加到新名单。希望它可以帮助某人。下面是代码。

        node.h 文件

        #ifndef node_h
        #define node_h
        
        class LinkedList
        {
        
        private:
            struct node
            {
                int data;
                node *next;
            };
            node *head;
        
        public:
            LinkedList ();
            node *createNode (int key); 
            void appendNodeBack (const int &key);
            void printList ();
            int SumOfNodes (const LinkedList list1);
        };
        #endif
        

        node.cpp 文件

        #include "node.h"
        #include <math.h>
        
        LinkedList::LinkedList ():head(NULL) {}
        
        LinkedList::node *LinkedList::createNode (int key)
        {
            node *newNode = new node;
            newNode->data = key;
            newNode->next = NULL;
            return newNode;
        }
        
        void LinkedList::appendNodeBack (const int &key)
        {
            node *newNode = createNode (key);
        
            //if tree is empty
            if (head == NULL)
            {
                head = newNode;
                return;
            }
        
            //if tree is not empty
            //traverse to the last node in the list
            node *temp = head;
            while (temp->next != NULL)
                temp = temp->next;
            temp->next = newNode;
        }
        
        void LinkedList::printList ()
        {
            //if tree is empty
            if (head == NULL)
            {
                std::cout << "Tree is empty!\n";
                return;
            }
        
            //if tree not empty
            node *temp = head;
            while (temp != NULL)
            {
                std::cout << temp->data<<"-->";
                temp = temp->next;
        
            }
            std::cout << "NULL\n";
        }
        
        int LinkedList::SumOfNodes (const LinkedList list1)
        {   
            //find the length of the list
            node *temp = head;
            int count = 0;
        
            while (temp != NULL)
            {
                count++;
                temp = temp->next;
            }
        
            //re-assign temp to head
            temp = head;
        
            //calculate the sum
            unsigned int sum = 0;
        
            for (unsigned int i = 1; i < pow (10, count); i = i * 10)
            {
                sum = sum + temp->data * i;
                temp = temp->next;
            }
        
            return sum;
        }
        

        main.cpp 文件

        #include <iostream>
        #include "node.cpp"
        
        int main ()
        {
            LinkedList list1, list2, list3;
            list1.appendNodeBack (2);
            list1.appendNodeBack (3);
            list1.appendNodeBack (5);
            list1.appendNodeBack (4);
        
            list2.appendNodeBack (5);
            list2.appendNodeBack (6);
            list2.appendNodeBack (7);
            list2.appendNodeBack (8);
        
            list1.printList ();
            std::cout << list1.SumOfNodes (list1) << std::endl;
        
            list2.printList ();
            std::cout << list2.SumOfNodes (list2) << std::endl;
        
            unsigned int sum = list1.SumOfNodes (list1) + list2.SumOfNodes (list2);
        
            //convert the number to string
            std::string str = std::to_string (sum);
        
            //append integer value to the new list
            for (unsigned int i = 0; i < str.length (); i++)
                list3.appendNodeBack (int (str[i] - '0'));
        
            std::cout << "The new list becomes\n";
            list3.printList();
        
            return 0;
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-11-30
          • 2019-06-23
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多