学习了链表结构,链表中元素的访问,对象指针的初始化与赋值,链表的创建(多个节点链接起来),进位计算的表达。
100ms
/*** 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* sum = new ListNode(0);ListNode* tmp = sum;int carry = 0; while(l1 || l2) {if(l1){carry += l1->val;l1 = l1->next;}if(l2){carry += l2->val;l2 = l2->next;}tmp->next = new ListNode(carry % 10);carry /= 10;tmp = tmp->next;}if(carry)tmp->next = new ListNode(carry);return sum->next;} };
68ms
class Solution { public:ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {ListNode *L = new ListNode(0), *p = L;int m = 0; //进位值int x, y; //保存l1 l2节点的值while(l1 || l2){ //题目中的链表是没有header的x = (l1 != NULL) ? l1->val : 0;y = (l2 != NULL) ? l2->val : 0;p->val = (x + y + m) % 10;m = (x + y + m) > 9;cout << x << y << m << endl;l1 = (l1 != NULL) ? l1->next : NULL;l2 = (l2 != NULL) ? l2->next : NULL;p->next = ((l1 || l2) || m != 0) ? new ListNode(m) : NULL; // 如果仅判断(l1 || l2)的话,5+5 的情况会丢失进位p ? p = p->next : 0;}return L;} };