【爆刷力扣-链表】画图自见

【leetcode 24】两两交换链表中的节点

关于cur指向

cur指向反转结点的前一结点

eg1 : (1,2) cur->dummyHead

eg2 : (3,4) cur->2

关于终止条件

奇数 偶数

操作顺序

初始时,cur指向虚拟头结点,然后进行如下三步:

操作之后,链表如下:

看这个可能就更直观一些了:

代码

伪代码

cpp 复制代码
dummyHead -> next = head;
cur = dummyHead;
while(cur -> next != NULL && cur ->next -> next != NULL){//要注意这个顺序,反过来发生空指针异常
    temp = cur ->next;
    temp1 = cur ->next ->next ->next;
    
    cur ->next = cur ->next ->next;
    cur ->next ->next = temp;
    temp ->next = temp1;
    cur = cur ->next ->next;
}
return dummyHead ->next;

代码

cpp 复制代码
class Solution {
public:
    ListNode* swapPairs(ListNode* head) {
        ListNode* dummyHead = new ListNode(0); // 设置一个虚拟头结点
        dummyHead->next = head; // 将虚拟头结点指向head,这样方便后面做删除操作
        ListNode* cur = dummyHead;
        while(cur->next != nullptr && cur->next->next != nullptr) {
            ListNode* tmp = cur->next; // 记录临时节点
            ListNode* tmp1 = cur->next->next->next; // 记录临时节点

            cur->next = cur->next->next;    // 步骤一
            cur->next->next = tmp;          // 步骤二
            cur->next->next->next = tmp1;   // 步骤三

            cur = cur->next->next; // cur移动两位,准备下一轮交换
        }
        ListNode* result = dummyHead->next;
        delete dummyHead;
        return result;
    }
};
  • 时间复杂度:O(n)
  • 空间复杂度:O(1)

【leetcode 160】相交链表

cpp 复制代码
class Solution {
public:
    ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
        ListNode* curA = headA;
        ListNode* curB = headB;
        int lenA = 0;
        int lenB = 0;
        while(curA){
            lenA++;
            curA = curA ->next;
        }
        while(curB){
            lenB++;
            curB = curB -> next;
        }
        ListNode* longList = headA;
        ListNode* shortList = headB;
        if(lenB > lenA){
            longList = headB;
            shortList = headA;
        }

        int gap = abs(lenA - lenB);
        while(gap--){
            longList = longList -> next;
        }
        while(longList){
            if(longList == shortList){
                return longList;
            }
            longList = longList ->next;
            shortList = shortList -> next;
        }
        return NULL;
    }
};
相关推荐
Aczone2818 小时前
硬件(六)arm指令
开发语言·汇编·arm开发·嵌入式硬件·算法
luckys.one1 天前
第9篇:Freqtrade量化交易之config.json 基础入门与初始化
javascript·数据库·python·mysql·算法·json·区块链
~|Bernard|1 天前
在 PyCharm 里怎么“点鼠标”完成指令同样的运行操作
算法·conda
战术摸鱼大师1 天前
电机控制(四)-级联PID控制器与参数整定(MATLAB&Simulink)
算法·matlab·运动控制·电机控制
Christo31 天前
TFS-2018《On the convergence of the sparse possibilistic c-means algorithm》
人工智能·算法·机器学习·数据挖掘
好家伙VCC1 天前
数学建模模型 全网最全 数学建模常见算法汇总 含代码分析讲解
大数据·嵌入式硬件·算法·数学建模
liulilittle1 天前
IP校验和算法:从网络协议到SIMD深度优化
网络·c++·网络协议·tcp/ip·算法·ip·通信
bkspiderx1 天前
C++经典的数据结构与算法之经典算法思想:贪心算法(Greedy)
数据结构·c++·算法·贪心算法
中华小当家呐1 天前
算法之常见八大排序
数据结构·算法·排序算法
沐怡旸1 天前
【算法--链表】114.二叉树展开为链表--通俗讲解
算法·面试