题目:
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.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
<pre name="code" class="cpp">/**
* 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) {
if(l1==NULL)
return l2;
if(12==NULL)
return l1;
int carry=0;
int temp;
temp = (l1?l1->val:0)+(l2?l2->val:0)+carry;
ListNode *head = new ListNode(temp%10);
ListNode *curr=head;
l1?l1=l1->next:0;
l2?l2=l2->next:0;
carry = temp/10;
while(l1||l2||carry) {
temp =(l1?l1->val:0)+(l2?l2->val:0)+carry;
curr->next = new ListNode(temp%10);
curr = curr->next;
carry = temp/10;
l1?l1=l1->next:0;
l2?l2=l2->next:0;
}
return head;
}
};
关于链表的其他操作:
//由数组创建单链表
ListNode *CreateList(int *A,int N)
{
if(A == NULL)
return NULL;
ListNode *head =new ListNode(A[0]);
ListNode *p =head;
for(int i=1;i<N;i++)
{
p->next = new ListNode(A[i]);
p = p->next;
}
return head;
}
//显示单链表
void ShowList(ListNode *L)
{
ListNode *p =L;
while(p)
{
cout<<p->val<<" ";
p = p->next;
}
}
参考地址: http://www.doc88.com/p-701223965112.html