Problem Description:
You are given, linked lists representing, and non-negative numbers. The digits is stored in reverse order and all of their nodes contain a single digit. ADD the numbers and return it as a linked list.
Input: (2, 4, 3) + (5, 6, 4)
Output: 7, 0, 8
Analysis: According to test instructions, according to the data structure of the linked list to add two numbers, mainly to investigate the chain list operation. A two-linked list can be traversed with two pointers. Be aware that there may be rounding in the end. The case where a node needs to be added, the detailed code such as the following:
/** * 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 *p=l1, *q=l2; ListNode *head=null,*cur=null; if (!p&&!q) return head; int flag=0; while (p&&q) {int value= (p->val+q->val+flag)%10; flag= (P->val+q->val+flag)/10; ListNode *temp=new ListNode (value); if (!cur) {cur=temp; Head=cur; } else {cur->next=temp; Cur=temp; } p=p->next; q=q->next; } while (p) {int value= (p->val+flag)%10; flag= (P->val+flag)/10; p->val=value; cur->next=p; Cur=p; p=p-≫next; } while (q) {int value= (q->val+flag)%10; flag= (Q->val+flag)/10; q->val=value; cur->next=q; cur=q; q=q->next; } if (flag==1) {ListNode *temp=new ListNode (1); cur->next=temp; } return head; }};
Copyright notice: This article Bo Master original articles, blogs, without consent may not be reproduced.
Leetcode--add Numbers