Add Two Numbers
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Add Two Numbers相关的知识,希望对你有一定的参考价值。
You are given two linked lists representing two non-negative numbers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {}//构造函数 * }; */ class Solution { public: ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { ListNode dummy(0);//为带头结点的链表
ListNode* p = &dummy; int cn = 0;//表示进位 while(l1 || l2) { int val = cn + (l1 ? l1->val : 0) + (l2 ? l2->val : 0); cn = val / 10; val = val % 10;//表示当前位 p->next = new ListNode(val);//申请新结点用来储存val,并利用构造函数初始化 p = p->next;//形成链表 if(l1) { l1 = l1->next; } if(l2) { l2 = l2->next; } } if(cn != 0) { p->next = new ListNode(cn); p = p->next; }//判断最高位 return dummy.next; } };
以下是带结节点链表初始化操作
#include<iostream> using namespace std; struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {}//构造函数 }; int main(){ ListNode list(0),*rear(0),*head(0); rear=&list; int n; while(cin>>n){ rear->next=new ListNode(n); rear=rear->next; }//以ctr+z结束 head=list.next; while(head){ cout<<head->val<<" "; head=head->next; } return 0; }
以上是关于Add Two Numbers的主要内容,如果未能解决你的问题,请参考以下文章