C++刷题笔记:链表


两数相加

在这里插入图片描述
考虑创建哑节点dummy,使用dummy->next表示真正的头节点,避免空边界. 时间复杂度 O(n)O(n)

/**
 * 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* first = new ListNode(0);  // 哑结点
        ListNode* last = first;
        int carry = 0;
        while(l1 or l2 or carry){
            // 相加
            int bitsum = 0;
            if(l1){
                bitsum += l1->val;
                l1 = l1->next;
            }
            if(l2){
                bitsum += l2->val;
                l2 = l2->next;
            }
            if(carry){
                bitsum += carry;
            }
            // 结果
            int digit = bitsum % 10;
            carry = bitsum / 10;
            // 链表存储
            ListNode* node = new ListNode(digit);
            last->next = node;
            last = node;
        }
        last = first->next;
        delete first;
        return last;
    }
};

反转链表输出

struct ListNode {
      int val;
      struct ListNode *next;
      ListNode(int x) : val(x), next(NULL) {}
};

方法一:使用std::reverse()反转链表的输出vector

class Solution {
public:
    vector<int> printListFromTailToHead(ListNode* head) {
	    std::vector<int> ret;
        while(head!=nullptr){
            ret.push_back(head->val);
            head= head->next;
        }
        //再开辟内存,逆序遍历
        //for(auto iter=arr.rbegin(); iter<arr.rend();iter++){
        //    ret.push_back(*iter);
        //}
        std::reverse(ret.begin(), ret.end());
        return ret;
    }
};

方法二:直接反转链表,改变指针指向

在这里插入图片描述

class Solution {
public:
    vector<int> printListFromTailToHead(ListNode* head) {
        ListNode* newHead  = nullptr;
        ListNode* node;  // 存放删除的结点,也是新插入的结点
        while(head){
            node = head;            // 保存删除
            head = head->next;      // 更新头
            node->next = newHead;   // 重新插入
            newHead = node;         // 更新头
        }
        
        std::vector<int> ret;
        while(newHead){
            ret.push_back(newHead->val);
            newHead = newHead->next;
        }
        return ret;
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章