DAY5 - 链表(一)

链表算是常出的题型之一吧(?
今天先整理出相对直观好理解的题目,明天补上比较需要思考的
链表也不需要多介绍了,直接上题目整理


例题实战

206.反转链表
这个应该是讲到烂了..但还是写一下吧

[法一]迭代

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* reverseList(ListNode* head) {
        if(head==nullptr||head->next==nullptr){
            return head;
        }
        //2->1->3
        //2<-1<-3
        ListNode* f = nullptr, *c = head, *c_next = head->next;
        while(c){
            c_next = c->next;
            c->next = f;
            f = c;
            c = c_next;
        }
        return f;
    }
};

[法二] 递回

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* reverseList(ListNode* head) {
        if(head==nullptr||head->next==nullptr){
            return head;
        }
        //2-> 1<-3<-5
        //1<-3<-5<-2
        ListNode* new_head = reverseList(head->next);//返回子链的head节点
        head->next->next = head;
        head->next = nullptr;
        return new_head;
    }
};

21.合并有序链表
这题在排序的文章中讲过了,就不写了


160.相交链表
这题很有趣,从两端开始走,走到底就到另一端的头部,最後相遇就是交点!!

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
        if(headA==nullptr||headB==nullptr){
            return nullptr;
        }
        ListNode* pA = headA, *pB = headB;
        while(pA!=pB){
            pA = pA==nullptr?headB:pA->next;
            pB = pB==nullptr?headA:pB->next;
        }
        return pA;
    }
};

<<:  第05天 - 一些些的Bootstrap、CSS

>>:  [Day-5] R语言 - 分群前处理 ( Clustering Preprocessing )

Day 02: ML基础第二步 Anaconda开发环境

前言 Python虽然可以直接使用Windows的Console直接执行程序,但是不只对於笔者,对於...

【Day 07】开始谈论主程序啦!!!

某一天我们提到,主要的逻辑都写在 django_chatbot/views.py。 但是里面牵涉太多...

Day 25 埠映射与记忆体映射

输出与输入设备是在嵌入式系统里面,占有一个很重要的位置,所有的输入输出系统都必须透过设备控制暂存器,...

【Tailwind CSS 教学 - 14】透过 Tailwind 达到容器与内容分离

影片重点 以 Tailwind 来讲解如何达到容器与内容分离 Codepen Demo 示范流程 ...

[NestJS 带你飞!] DAY21 - HTTP Module

很多时候我们会需要去串接第三方的 API,例如:绿界科技的金流服务、Binance 的 API 等,...