题目:
You are given two non-empty linked lists representing two non-negative integers. 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.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Example:
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) Output: 7 -> 0 -> 8 Explanation: 342 + 465 = 807.
代码(C++实现):
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 // 结果链表的首节点 13 ListNode *head = nullptr; 14 // 尾插法建立单链表指向尾节点 15 ListNode *tail = nullptr; 16 // num1为两整数相加后的个位数值 17 int num1 = 0; 18 // num2为两整数相加后的进位数值 19 int num2 = 0; 20 // node1Val为l1当前节点的数据域或者0 21 int node1Val = 0; 22 // node2Val为l2当前节点的数据域或者0 23 int node2Val = 0; 24 // count变量的设置是为了尾插法建立单链表设置的计数器 25 int count = 0; 26 27 while(l1 != nullptr || l2 != nullptr) 28 { 29 // 如果节点不为空,则取节点的数据域否则让节点的数据域为0 30 if(l1 == nullptr) 31 { 32 node1Val = 0; 33 }else 34 { 35 node1Val = l1->val; 36 } 37 if(l2 == nullptr) 38 { 39 node2Val = 0; 40 }else 41 { 42 node2Val = l2->val; 43 } 44 // 本次计算结果 = 本次计算的node1Val + 本次计算的node1Va2 + 进位值 45 num1 = node1Val + node2Val + num2; 46 if(num1 >= 10) 47 { 48 num1 = num1 - 10; 49 num2 = 1; 50 }else 51 { 52 num2 = 0; 53 } 54 // 为建立结果链表创建节点 55 ListNode *newNode = new ListNode(num1); 56 // 尾插法建立结果单链表,如果是首节点,需要进行特殊处理 57 if(count == 0) 58 { 59 head = tail = newNode; 60 }else 61 { 62 tail->next = newNode; 63 tail = newNode; 64 } 65 // 链表向前移动并释放原始链表所占的内存空间 66 if(l1 != nullptr) 67 { 68 ListNode *tempNode1 = l1; 69 l1 = l1->next; 70 delete tempNode1; 71 } 72 if(l2 != nullptr) 73 { 74 ListNode *tempNode2 = l2; 75 l2 = l2->next; 76 delete tempNode2; 77 } 78 79 /* 为了解决例如情况:l1 = [5] 80 l2 = [5] 81 这种情况 82 */ 83 if(l1 == nullptr && l2 == nullptr && num2 != 0) 84 { 85 ListNode *newNode = new ListNode(num2); 86 tail->next = newNode; 87 tail = newNode; 88 return head; 89 } 90 count++; 91 92 } 93 94 return head; 95 } 96 };
原文地址:https://www.cnblogs.com/xuelisheng/p/10770215.html
时间: 2024-10-29 19:13:33