LeetCode2 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. (Medium)
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
分析:
链表操作题,算法没什么复杂的,注意语言上不出问题就行,其次对于写法要尽可能简练,自己第一种写法就很冗长,改进后得到方法2。
链表注意:空表判断,dummy node应用等
代码1:
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 public: 11 ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { 12 if (l1 == nullptr) { 13 return l2; 14 } 15 if (l2 == nullptr) { 16 return l1; 17 } 18 ListNode dummy(0); 19 ListNode* result; 20 dummy.next = result; 21 result = &dummy; 22 int carry = 0; 23 while (l1 != nullptr && l2 != nullptr ) { 24 ListNode* newNode = new ListNode(0); 25 result -> next = newNode; 26 int temp = l1 -> val + l2 -> val + carry; 27 if (temp >= 10){ 28 carry = 1; 29 newNode -> val = temp - 10; 30 } 31 else{ 32 carry = 0; 33 newNode -> val = temp; 34 } 35 l1 = l1 -> next; 36 l2 = l2 -> next; 37 result = newNode; 38 } 39 40 if (l1 != nullptr) { 41 while (l1 != nullptr) { 42 ListNode* newNode = new ListNode(0); 43 //仍然有可能进位! 44 int temp = carry + l1 -> val; 45 if (temp >= 10){ 46 carry = 1; 47 newNode -> val = temp - 10; 48 } 49 else{ 50 carry = 0; 51 newNode -> val = temp; 52 } 53 result -> next = newNode; 54 result = newNode; 55 l1 = l1 -> next; 56 } 57 } 58 if (l2 != nullptr) { 59 while (l2 != nullptr) { 60 ListNode* newNode = new ListNode(0); 61 int temp = carry + l2 -> val; 62 if (temp >= 10){ 63 carry = 1; 64 newNode -> val = temp - 10; 65 } 66 else{ 67 carry = 0; 68 newNode -> val = temp; 69 } 70 result -> next = newNode; 71 result = newNode; 72 l2 = l2 -> next; 73 } 74 } 75 if(carry == 1){ 76 ListNode* newNode = new ListNode(0); 77 newNode -> val = 1; 78 result -> next = newNode; 79 } 80 return dummy.next; 81 } 82 };
各种条件判定过于繁琐,代码又臭又长...
改进后将l1,l2,carry的判断放在一起处理,同时用/ 和 %代替if语句 得到代码2
代码2:
1 class Solution { 2 public: 3 ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { 4 ListNode dummy(0); 5 ListNode* result = & dummy; 6 int carry = 0; 7 while (l1 != nullptr || l2 != nullptr || carry == 1 ) { 8 result -> next = new ListNode(0); 9 result = result -> next; 10 int tempVal = 0; 11 if (l1 != nullptr) { 12 tempVal += l1 -> val; 13 l1 = l1 -> next; 14 } 15 if (l2 != nullptr) { 16 tempVal += l2 -> val; 17 l2 = l2 -> next; 18 } 19 if (carry == 1) { 20 tempVal++; 21 } 22 //不用if判断 23 result -> val = tempVal % 10; 24 carry = tempVal / 10; 25 } 26 return dummy.next; 27 } 28 };