两个链表生成相加链表

题目

描述
假设链表中每一个节点的值都在 0 - 9 之间,那么链表整体就可以代表一个整数。
给定两个这种链表,请生成代表两个整数相加值的结果链表。
数据范围:0≤n,m≤1000000,链表任意值 0≤val≤9
要求:空间复杂度 O(n),时间复杂度 O(n)
例如:链表 1 为 9->3->7,链表 2 为 6->3,最后生成新的结果链表为 1->0->0->0。

思路

按照小学学的两个数相加的运算方法,一位对应一位相加然后进到高位。所以我们将链表反转,然后对应位置相加的值存起来。如果一个链表更长,那么将剩下的和之前进的数相加继续传递下去,最后storage里面存的就是结果,然后根据这个结果创建新的链表。

代码

python版本:

# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
# 
# @param head1 ListNode类 
# @param head2 ListNode类 
# @return ListNode类
#
class Solution:
    def addInList(self , head1: ListNode, head2: ListNode) -> ListNode:
        # write code here
        reverse_head1, num1 = self.reverse(head1)
        reverse_head2, num2 = self.reverse(head2)
        carry = 0
        storage = []
        while(reverse_head1 != None and reverse_head2 != None):
            per_node_val = reverse_head1.val + reverse_head2.val + carry
            storage.append(per_node_val%10)
            carry = 1 if per_node_val>= 10 else 0
            reverse_head1 = reverse_head1.next
            reverse_head2 = reverse_head2.next
        rest = reverse_head1 if num1>num2 else reverse_head2
        while(rest != None):
            rest_val = rest.val+carry
            storage.append(rest_val%10)
            carry = 1 if rest_val>= 10 else 0
            rest = rest.next
            
        if carry != 0:
            storage.append(carry)
        new_node = ListNode(-1)
        sg = new_node
        while(storage):
            new_node.next = ListNode(storage.pop())
            new_node = new_node.next
        return sg.next
    
    def reverse(self, head: ListNode)-> ListNode: 
        pre = None
        cur = head
        num = 0
        while(cur):
            num+=1
            tmp = cur.next
            cur.next = pre
            pre = cur
            cur = tmp
        return pre, num

c++版本

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */

class Solution {
public:
    /**
     * 
     * @param head1 ListNode类 
     * @param head2 ListNode类 
     * @return ListNode类
     */
    ListNode* addInList(ListNode* head1, ListNode* head2) {
        // write code here
        ListNode *last1;
        ListNode *last2;
        ListNode *pre1 = NULL;
        ListNode *cur1 = head1;
        int num1 = 0;
        int num2 = 0;
        while(cur1){
            num1++;
            ListNode *tmp1 = cur1->next;
            cur1->next = pre1;
            pre1 = cur1;
            cur1 = tmp1;
        }
        last1 = pre1;
        
        ListNode *pre2 = NULL;
        ListNode *cur2 = head2;
        while(cur2){
            ListNode *tmp2 = cur2->next;
            cur2->next = pre2;
            pre2 = cur2;
            cur2 = tmp2;
        }
        last2 = pre2;
        int carry=0;
        stack<int> storage;
        while(last1 && last2){
            num2++;
            int per_val = last1->val+last2->val+carry;
            carry = per_val>=10 ? 1 : 0;
            storage.push(per_val%10);
            last1 = last1->next;
            last2 = last2->next;
            }
        ListNode *rest = num1 > num2 ? last1 : last2;
        while(rest){
            int rest_val = rest->val+carry;
            carry = rest_val>=10 ? 1 : 0;
            storage.push(rest_val%10);
            rest = rest->next;
        }
        if(carry != 0){
            storage.push(carry);
        }
        
        ListNode *res = new ListNode(-1);
        ListNode *sg;
        sg = res;
        while(storage.size()){
            int val = storage.top();
            res->next = new ListNode(val);
            res = res->next;
            storage.pop();
        }
        return sg->next;
        }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
### 回答1: 链表可以用来实现多项式的相加,可以考虑以下步骤: 1. 定义一个节点表示多项式的每一项,包含两个成员变量:系数和指数。 2. 定义一个链表,每个节点表示多项式的一项。 3. 将多项式转换为链表,按照指数从高到低的顺序插入节点,如果插入的指数已经存在,则将系数相加。 4. 遍历两个链表,将对应指数的系数相加生成结果链表。 以下是一个 C++ 代码示例: ```cpp #include <iostream> using namespace std; struct PolyNode { int coef; // 系数 int expn; // 指数 PolyNode* next; }; void createPolyList(PolyNode*& head) { int n; cout << "请输入多项式项数:"; cin >> n; head = new PolyNode; head->next = NULL; PolyNode* p = head; for (int i = 1; i <= n; i++) { PolyNode* node = new PolyNode; cout << "请输入第" << i << "项的系数和指数:"; cin >> node->coef >> node->expn; node->next = NULL; p->next = node; p = node; } } void printPolyList(PolyNode* head) { PolyNode* p = head->next; while (p) { cout << p->coef << "x^" << p->expn; p = p->next; if (p) cout << " + "; } cout << endl; } void addPolyList(PolyNode* head1, PolyNode* head2, PolyNode*& head3) { PolyNode* p1 = head1->next; PolyNode* p2 = head2->next; head3 = new PolyNode; head3->next = NULL; PolyNode* p3 = head3; while (p1 && p2) { if (p1->expn < p2->expn) { PolyNode* node = new PolyNode; node->coef = p1->coef; node->expn = p1->expn; node->next = NULL; p3->next = node; p3 = node; p1 = p1->next; } else if (p1->expn > p2->expn) { PolyNode* node = new PolyNode; node->coef = p2->coef; node->expn = p2->expn; node->next = NULL; p3->next = node; p3 = node; p2 = p2->next; } else { PolyNode* node = new PolyNode; node->coef = p1->coef + p2->coef; node->expn = p1->expn; node->next = NULL; p3->next = node; p3 = node; p1 = p1->next; p2 = p2->next; } } while (p1) { PolyNode* node = new PolyNode; node->coef = p1->coef; node->expn = p1->expn; node->next = NULL; p3->next = node; p3 = node; p1 = p1->next; } while (p2) { PolyNode* node = new PolyNode; node->coef = p2->coef; node->expn = p2->expn; node->next = NULL; p3->next = node; p3 = node; p2 = p2->next; } } int main() { PolyNode* head1, * head2, * head3; createPolyList(head1); createPolyList(head2); addPolyList(head1, head2, head3); cout << "多项式1:"; printPolyList(head1); cout << "多项式2:"; printPolyList(head2); cout << "相加结果:"; printPolyList(head3); return 0; } ``` 该程序通过 createPolyList 函数创建两个多项式的链表,再通过 addPolyList 函数实现多项式相加,并将结果存储在 head3 中,最后通过 printPolyList 函数输出结果链表。 ### 回答2: 数据结构中的链表是由一系列节点组成的动态数据结构,其中每个节点包含两部分:数据域和指针域。数据域用于存储数据元素,而指针域用于指向下一个节点。 多项式相加是指将两个多项式相加得到一个新的多项式。多项式可以看作由一系列项组成,每个项包含一个系数和一个指数。例如,多项式4x^3 + 2x^2 + 5x + 1可以表示为链表的形式:(4, 3) -> (2, 2) -> (5, 1) -> (1, 0)。 对于链表的多项式相加,可以按照以下步骤进行操作: 1. 创建两个链表,用来存储两个多项式的和。 2. 从两个多项式的头节点开始,依次比较指数的大小。 3. 如果指数相同,将两个多项式的系数相加,并创建一个新节点将其存储到链表中。 4. 如果其中一个多项式的指数较小,将对应的节点复制到和链表中。 5. 继续以上步骤,直到遍历完两个多项式。 6. 如果有一个多项式还有项未处理,则将其余的项都复制到和链表中。 最终得到的和链表中包含了输入的两个多项式的和。我们可以根据需要对和链表进行进一步的处理,比如输出到屏幕上或者存储到文件中。 链表作为一种灵活而常用的数据结构,可以被广泛应用于多项式相加、图形算法等领域。通过合理地使用链表,我们可以高效地实现多项式相加的操作。 ### 回答3: 数据结构中,多项式的相加可以使用链表来实现。链表是一种常用的数据结构,它由一系列节点组成,每个节点包含一个数据元素和指向下一个节点的指针。 在多项式相加中,我们可以将每个项表示为一个节点,并按照指数从小到大的顺序插入到链表中。每个节点包含两个数据元素,一个是系数,另一个是指数,这样可以很方便地表示多项式的每一项。 首先,我们需要创建两个链表,分别表示两个多项式。然后,我们按照项的指数顺序将每个项插入到链表中。当插入时,我们需要比较当前项的指数与链表中已存在的项的指数大小来确定插入位置。 在插入过程中,如果遇到两个节点的指数相同,我们需要将它们的系数相加并更新对应节点的系数值。如果链表中不存在对应的指数,则直接将新的节点插入到链表中。 最后,我们可以将链表中的每个节点打印出来,即可得到多项式相加的结果。需要注意的是,我们在输出结果时,可以根据节点的系数值是否为零来决定是否输出该项,以避免输出不必要的项。 使用链表来实现多项式的相加,可以保持多项式的有序性,同时避免使用数组或其他线性结构时的元素移动或扩容操作,提高了插入和删除的效率。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

超超爱AI

土豪请把你的零钱给我点

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值