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

【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;
    }
};
相关推荐
NAGNIP18 分钟前
一文搞懂机器学习中的特征降维!
算法·面试
NAGNIP34 分钟前
一文搞懂机器学习中的特征构造!
算法·面试
Learn Beyond Limits1 小时前
解构语义:从词向量到神经分类|Decoding Semantics: Word Vectors and Neural Classification
人工智能·算法·机器学习·ai·分类·数据挖掘·nlp
你怎么知道我是队长1 小时前
C语言---typedef
c语言·c++·算法
Qhumaing3 小时前
C++学习:【PTA】数据结构 7-1 实验7-1(最小生成树-Prim算法)
c++·学习·算法
Z1Jxxx4 小时前
01序列01序列
开发语言·c++·算法
汽车仪器仪表相关领域6 小时前
全自动化精准检测,赋能高效年检——NHD-6108全自动远、近光检测仪项目实战分享
大数据·人工智能·功能测试·算法·安全·自动化·压力测试
Doro再努力6 小时前
【数据结构08】队列实现及练习
数据结构·算法
清铎8 小时前
leetcode_day12_滑动窗口_《绝境求生》
python·算法·leetcode·动态规划