标签:
No.2 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.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
单链表实现两数相加:
用链表表示两两非负数,数字的存储是倒序的,并且每个结点包含一位数,将两数相加返回链表形式(也是倒序的)
如:Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
参考:书
1 /** 2 * Definition for singly-linked list. 3 * struct ListNode { 4 * int val; 5 * ListNode *next; 6 * ListNode(int x) : val(x), next(NULL) {} 7 * }; 8 */ 9 class Solution 10 { 11 public: 12 ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) 13 { 14 /* 15 两数相加: 16 用链表表示两两非负数,数字的存储是倒序的,并且每个结点包含一位数,将两数相加返回链表形式(也是倒序的) 17 如:Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) 18 Output: 7 -> 0 -> 8 19 */ 20 ListNode head(-1); 21 ListNode *p = &head; 22 23 int carry = 0;//进位只能为0和1吗? 24 int sum = 0; 25 int data1 = 0; 26 int data2 = 0; 27 while(l1 != NULL || l2 != NULL) 28 { 29 if(l1==NULL) 30 data1 = 0; 31 else 32 { 33 data1 = l1->val; 34 l1 = l1->next;//!!! 35 } 36 if(l2 == NULL) 37 data2 = 0; 38 else 39 { 40 data2 = l2->val; 41 l2 = l2->next;//!!! 42 } 43 44 sum = data1 + data2 + carry; 45 46 carry = sum/10; 47 p->next = new ListNode(sum%10); 48 p = p->next; 49 } 50 if(carry > 0) 51 p->next = new ListNode(carry); 52 53 return head.next; 54 55 } 56 };
或,更简单
1 /** 2 * Definition for singly-linked list. 3 * struct ListNode { 4 * int val; 5 * ListNode *next; 6 * ListNode(int x) : val(x), next(NULL) {} 7 * }; 8 */ 9 class Solution 10 { 11 public: 12 ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) 13 { 14 /* 15 两数相加: 16 用链表表示两两非负数,数字的存储是倒序的,并且每个结点包含一位数,将两数相加返回链表形式(也是倒序的) 17 如:Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) 18 Output: 7 -> 0 -> 8 19 */ 20 ListNode head(-1); 21 ListNode *p = &head; 22 23 int carry = 0;//进位只能为0和1吗? 24 int sum = 0; 25 int data1 = 0; 26 int data2 = 0; 27 while(l1 != NULL || l2 != NULL) 28 { 29 data1 = 0; 30 data2 = 0; 31 if(l1!=NULL) 32 { 33 data1 = l1->val; 34 l1 = l1->next;//!!! 35 } 36 if(l2 != NULL) 37 { 38 data2 = l2->val; 39 l2 = l2->next;//!!! 40 } 41 42 sum = data1 + data2 + carry; 43 44 carry = sum/10; 45 p->next = new ListNode(sum%10); 46 p = p->next; 47 } 48 if(carry > 0) 49 p->next = new ListNode(carry); 50 51 return head.next; 52 53 } 54 };
标签:
原文地址:http://www.cnblogs.com/dreamrun/p/4544259.html