[LeetCode]LinkedList主题系列{第2题}

时间:2022-05-06
本文章向大家介绍[LeetCode]LinkedList主题系列{第2题},主要内容包括1.内容介绍、2.题目和解题过程、基本概念、基础应用、原理机制和需要注意的事项等,并结合实例形式分析了其使用技巧,希望通过本文能帮助到大家理解应用这部分内容。

1.内容介绍

本篇文章记录在leetcode中LinkedList主题下面的题目和自己的思考以及优化过程,具体内容层次按照{题目,分析,初解,初解结果,优化解,优化解结果,反思}的格式来记录,供日后复习和反思[注:有些题目的解法比较单一,就没有优化过程]。题目的顺序按照leetcode给出的题目顺序,有些题目在并不是按照题目本身序号顺序排列的,也不是严格按照难易程度来排列的。

因此,这篇文章并不具有很强的归类总结性,归类总结性知识将会在其他文章记录,本篇重点在记录解题过程中的思路,希望能对自己有所启发。

2.题目和解题过程

2.1 Add Two Numbers

  • 题目: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.
  • 分析:题目考察对链表的遍历和生成过程,需要严格注意对指针的操作。
  • 初解:分别从两个链表表头开始遍历,取每个结点的值然后求和计算进位值和余数值,并生成新的结点来存储余数值,将进位值向后传递,直到两个链表都遍历完毕,最终再检查是否还存在进位值即可;其中最重要的是题目要求返回结果链表的表头指针,而该链表又是单链表,因此需要使用指针的指针。
/**
 * 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* head = nullptr;
        ListNode** ptr = &head;//重点在此,必须使用指针的指针,如果使用单纯的指针则无法改变head的内容,如果使用引用则使得最终head指向链表末尾
        ListNode* a = l1;
        ListNode* b = l2;
        int carry = 0;
        while(a!=nullptr || b!=nullptr)
        {
            int sum = 0;
            if(a!=nullptr && b!=nullptr)
            {
                sum = a->val + b->val + carry;
                a = a->next;
                b = b->next;
            }
            else if(a!=nullptr) 
            {
                sum = a->val + carry; 
                a = a->next;
            }
            else 
            {
                sum = b->val + carry;
                b = b->next;
            }
            
            carry = (sum >= 10)? 1:0;
            int mod = sum - carry * 10;
            ListNode* next = new ListNode(mod);
            *ptr=next;
            ptr =&(next->next);
        }
        if(carry != 0)
        {
            ListNode* next = new ListNode(carry);
            *ptr= next;
            ptr=&(next->next);
        }
        return head;
    }
};
  • 初解结果:
  • 反思:若是仅仅对链表进行遍历而不修改源链表,则只使用指针即可,若是需要对链表内容进行修改但不改动指针的位置,则需要使用指针的指针。