#include <iostream> using namespace std; struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {} }; class Solution { public: ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) { int temp=0; ListNode *head,*Node; Node=new ListNode(0); head=Node; while (1) { //两个非空 if (l1!=NULL && l2!=NULL) { if ((l1->val+l2->val+temp)>=10) { Node->val=(l1->val+l2->val+temp)-10; temp=1; } else { Node->val=(l1->val+l2->val+temp); temp=0; } if (l1->next || l2->next) { ListNode *temp_link; temp_link=new ListNode(0); Node->next=temp_link; Node=temp_link; } l1=l1->next; l2=l2->next; } //有一个非空 else if(l1==NULL && l2!=NULL) { if ((l2->val+temp)>=10) { Node->val=l2->val+temp-10; temp=1; } else { Node->val=l2->val+temp; temp=0; } if (l2->next) { ListNode *temp_link; temp_link=new ListNode(0); Node->next=temp_link; Node=temp_link; } l2=l2->next; } //一个非空 else if(l2==NULL && l1!=NULL) { if ((l1->val+temp)>=10) { Node->val=(l1->val+temp)-10; temp=1; } else { Node->val=(l1->val+temp); temp=0; } if (l1->next) { ListNode *temp_link; temp_link=new ListNode(0); Node->next=temp_link; Node=temp_link; } l1=l1->next; } //两个都为空 else { if (temp>0) { ListNode *temp_link; temp_link=new ListNode(0); Node->next=temp_link; Node=temp_link; Node->val=temp; } break; } } return head; } }; int main() { ListNode *node,*head; node =new ListNode(0); head=node; int data_in; cin>>data_in; node->val=data_in; while(1) { cin>>data_in; if (data_in==0) { break;; } ListNode *temp; temp=new ListNode(0); temp->val=data_in; node->next=temp; node=temp; } ListNode *node2,*head2; node2=new ListNode(1); head2=node2; int data_in2; cin>>data_in2; node2->val=data_in2; while(1) { cin>>data_in2; if (data_in2==0) { break; } ListNode *temp2; temp2=new ListNode(1); temp2->val=data_in2; node2->next=temp2; node2=temp2; } Solution sd; ListNode *temp3=sd.addTwoNumbers(head,head2); system("pause"); return 0; } </iostream>