c_cpp 添加由链接列表表示的两个数字

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了c_cpp 添加由链接列表表示的两个数字相关的知识,希望对你有一定的参考价值。

// https://www.geeksforgeeks.org/add-two-numbers-represented-by-linked-lists/
#include <iostream>
#include <list>
using namespace std;

struct linked_list {
    int data;
    struct linked_list *next;
};
typedef struct linked_list node;

void print (node* n) {
    while (n) {
        cout<< n->data;
        n = n->next;
    }
    return;
}

void insert (node **headref, int n) {
    node* head = *headref;
    node *temp = new node;
    temp->data = n;
    temp->next = NULL;
    if (head == NULL) {
        *headref = temp;
        return;
    }
    while (head->next)
        head = head->next;
    head->next = temp;
    return;
}

void push(node** headref, int n) {
    node* temp = new node;
    temp->data = n;
    temp->next = *headref;
    *headref = temp;
}

node* ReverseList (node* head) {
    node* next = NULL, *current = head, *prev = NULL;
    while (current) {
        next = current->next;
        current->next = prev;
        prev=current;
        current = next;
    }
    return prev;
}

node* add(node** head1ref, node** head2ref) {
    node* head1 = *head1ref;
    node* head2 = *head2ref;
    node* head = NULL;
    head1 = ReverseList(head1);
    head2 = ReverseList(head2);

    int sum, carry = 0;
    while (head1 || head2) {
        sum = carry + (head1?head1->data:0) + (head2?head2->data:0);
        carry = (sum>9)?1:0;
        sum = sum%10;
        push(&head, sum);
        if (head1)
            head1 = head1->next;
        if (head2)
            head2 = head2->next;
    }
    if (carry>0)
        push(&head, carry);
    return head;
}

int main() {
    int n;
    node* head1 = NULL, *head2 = NULL;
    cout<< "Enter the first number\n";
    while (true) {
        cout<< "Enter the digit: ";
        cin>>n;
        if (n==-9)
            break;
        else
            insert(&head1, n);
    }
    cout<< "Enter the second number\n";
    while (true) {
        cout<< "Enter the digit: ";
        cin>>n;
        if (n==-9)
            break;
        else
            insert(&head2, n);
    }
    cout<< "First number is: ";
    print(head1);
    cout<< "\nSecond number is: ";
    print(head2);
    node* head=add(&head1, &head2);
    cout<< "\nSum of the numbers is: ";
    print(head);
}

以上是关于c_cpp 添加由链接列表表示的两个数字的主要内容,如果未能解决你的问题,请参考以下文章

c_cpp 给定已排序的链接列表,删除所有具有重复数字的节点,只留下原始列表中的不同数字。

c_cpp 两个排序链接列表的交集

c_cpp 合并两个已排序的链接列表

c_cpp 合并两个已排序的链接列表,使合并列表的顺序相反

c_cpp 160.两个链接列表的交集 - 简单 - 2018.8.6

c_cpp 给定两个表示为字符串的数字,将数字作为字符串返回乘法。注意:数字可以任意大