【ONE·基础算法 || 链表】

在这里插入图片描述

总言

  主要内容:编程题举例,熟悉理解单链表类题型。
  
  

  
  

1、链表

  常用技巧: 画图、引入虚拟头结点(算法题目汇总,多以无头结点的单向链表为主,若无虚拟头结点,有时需要考虑很多边界情况)、快慢双指针(在判环、判环入口、倒数第n个结点此类题型中很常用)
  操作总结: 创建新结点(new)、尾插、头插。
  
  以上涉及的练习题链接: 基础数据结构相关练习。同为单链表习题,建议作为本篇的补充习题,一并回顾重刷。
  
  
  
  
  
  

2、两数相加(medium)

  题源:链接

在这里插入图片描述

  

2.1、题解

  1)、思路分析
  链表逆序存储数字,方便了位运算。 两个链表的个位数、十位数等都已经对应,直接相加即可。但需要注意在相加过程中是否产生进位,若产生进位,则需要将进位加在当前位的下一位上,因此可以使用一个变量sum,来统计当前位相加结果。此外还需注意,即使两链表处理完成,sum中可能存在剩余值未处理。
  
  2)、题解

/**
 * 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* addTwoNumbers(ListNode* l1, ListNode* l2) {
        int sum = 0;//用于统计当前位相加结果
        ListNode* head = new ListNode;//哨兵位头结点
        // 双链表进行加操作
        ListNode *cur1 = l1, *cur2 = l2;//用于遍历两链表
        ListNode* tail = head;
        while (cur1 && cur2) {
            sum += cur1->val + cur2->val;
            tail->next = new ListNode(sum % 10);
            cur1 = cur1->next;
            cur2 = cur2->next;
            tail = tail->next;
            sum /= 10;
        }

        // 处理剩余链表情况
        while (cur1) {
            sum += cur1->val;
            tail->next = new ListNode(sum % 10);
            sum /= 10;
            cur1 = cur1->next;
            tail = tail->next;
        }
        while (cur2) {
            sum += cur2->val;
            tail->next = new ListNode(sum % 10);
            sum /= 10;
            cur2 = cur2->next;
            tail = tail->next;
        }
        //两链表处理完成,但sum可能存在剩余值未处理
        while(sum)
        {
            tail->next = new ListNode(sum%10);
            sum /=10;
        }
        //删除哨兵位头结点
        ListNode* next = head->next;
        delete head;
        return next;
    }
};

  简化版本:

class Solution {
public:
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
        int sum = 0;
        ListNode* head = new ListNode;
        ListNode* tail = head;
        ListNode* cur1 = l1, * cur2 = l2;

        while(cur1 || cur2 || sum)
        {
            if(cur1)
            {
                sum += cur1->val;
                cur1 = cur1->next;
            }

            if(cur2)
            {
                sum += cur2->val;
                cur2 = cur2->next;
            }

            tail->next = new ListNode(sum % 10);
            tail = tail->next;
            sum /= 10;
        }

        ListNode* next = head->next;
        delete head;
        return next;

    }
};

  
  
  

3、两两交换链表中的节点(medium)

  题源:链接

在这里插入图片描述

  
  

3.1、题解

  1)、思路分析
  此题主要在能将过程模拟出来。
在这里插入图片描述

  
  
  2)、题解

/**
 * 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* swapPairs(ListNode* head) {
        if (head == nullptr || head->next == nullptr)//边界情况处理,当结点个数>=2以上,才能满足下述指针使用。
            return head;

        ListNode* newhead = new ListNode;//哨兵位的头结点(方便)
        newhead->next = head;

        ListNode *prev = newhead, *cur = prev->next, *next = cur->next, *nnext = next->next;
        while (cur && next) {
            // 交换结点,更改关系
            prev->next = next;
            next->next = cur;
            cur->next = nnext;
            // 迭代:注意结点是否为空
            prev = cur;
            cur = nnext;
            if (cur)
                next = cur->next;
            if (next)
                nnext = next->next;
        }
        //处理尾部(也可不用处理,循环中的if语句已经处理过了)
        if(cur == nullptr) prev->next = nullptr;
        if(next == nullptr) cur->next = nullptr;

        head = newhead->next;
        delete newhead;
        return head;
    }
};

  
  
  
  
  
  

4、重排链表(medium)

  题源:链接

在这里插入图片描述

  
  

4.1、题解

  1)、思路分析
  根据题意,重排后的链表是从前往后选取一节点,从后往前再选取一节点。因此,我们可以先找到中间节点,将中间部分往后的逆序,然后再合并两个链表。
  PS :实则上述三步骤我们在之前的单链表习题中都学习过(求链表中间节点、翻转单链表、合并两个有序链表),这里是三则的结合与微调。
  
  2)、题解

/**
 * 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:
    void reorderList(ListNode* head) {
        if(head == nullptr || head->next == nullptr) return;//处理一下特殊情况,也可以把两个节点的算进来(没必要执行后续疯)
        
        //遍历,找中间结点
        ListNode* fast = head;
        ListNode* slow = head;
        ListNode* slowprev = nullptr;//主要是想处理一下尾结点。
        while(fast && fast->next)//双数&&单数情况
        {
            fast = fast->next->next;
            slowprev = slow;
            slow = slow->next;
        }
        slowprev->next = nullptr;//为了方便后续合并链表(这里将前后链表断开)

        //逆序后部分结点(这里使用的是头插法)
        ListNode* midhead = new ListNode;//后半部分的哨兵位头结点
        ListNode* cur = slow;
        while(cur)
        {
            ListNode* next = cur->next;//提前保存下一个结点
            cur->next = midhead->next;
            midhead->next = cur;
            cur = next;
        }

        //链表合并
        ListNode* cur1 = head;//用于遍历前半部分的链表
        ListNode* cur2 = midhead->next;//用于遍历后半部分的链表
        ListNode* tail =midhead;//借用一下midhead作为合并链表的哨兵位头节点
        while(cur1 && cur2)
        {
            //链接一个前半部分的节点
            tail->next = cur1;
            cur1 = cur1->next;
            tail = tail->next;

            //再链接一个后半部分的节点
            tail->next = cur2;
            cur2 = cur2->next;
            tail = tail->next;
        }
        while(cur2)//也可以用if,最多在节点为奇数时,后半部分链表会多一个节点需要额外处理
        {
            tail->next = cur2;
            cur2 = cur2->next;
        }

        head = midhead->next;
        delete midhead;
    }
};

  
  
  
  
  

5、合并 K 个升序链表(hard)

  题源:链接

在这里插入图片描述

  
  

5.1、使用优先级队列

  1)、思路分析
  使用暴力解法:时间复杂度大概在 O ( N K 2 ) O(NK^2) O(NK2)
在这里插入图片描述
  
  如何快速获取最小结点? 这里,我们可以借助数据结构堆(STL中的优先级队列),把每个链表的头结点放进⼀个小根堆中,这样就能快速的找到每次 K 个链表中,最小的元素是哪个。
  如何排序所有结点? 在从堆中取出堆顶结点时,将其下一个结点(next)存放入堆中,直到指向当前链表空结点处,如此,就能将所有结点排序。
在这里插入图片描述

  
  
  2)、题解

/**
 * 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) {}
 * };
 */

struct cmp {
    bool operator()(const ListNode* l1, const ListNode* l2) {
        return l1->val > l2->val;
    }
};

class Solution {
public:
    ListNode* mergeKLists(vector<ListNode*>& lists) {
        int k = lists.size(); // 链表个数
        std::priority_queue<ListNode*, std::vector<ListNode*>, cmp> Heap; // 建立小堆

        // 依次将链表头节点放入堆中。
        for(auto& e : lists)
        {
            if(e)//若当前链表不为空,将该节点放入堆中
                Heap.push(e);
        }

        // 取堆顶节点,尾插。
        ListNode* head = new ListNode(0); // 哨兵位的头结点:用于记录合并后的链表
        ListNode* tail = head;
        while(!Heap.empty())
        {   //取出堆顶元素
            ListNode* cur = Heap.top();
            Heap.pop();
            //尾插入合并链表中
            tail->next = cur;
            tail = tail->next;
            if(cur->next)//若当前链表不为空,将当前cur的后一个节点放入堆中
                Heap.push(cur->next);
        }
        tail->next = nullptr;

        ListNode* next = head->next;
        delete head;
        return next;
    }
};

  
  
  

5.2、分治:递归

  1)、思路分析
  借助分治的思想,vector<ListNode*>& lists,可知这K个链表都是放在数组中的,那么可将数组一分为二,先对左区间的链表进行合并,再对右区间的链表进行合并(即合并两个有序链表)。
  而对于左右两区间,又可重复上述分段合并的操作。
在这里插入图片描述
  
  
  2)、题解

/**
 * 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* merge(vector<ListNode*>& lists, int left, int right)
    {
        if(left > right) return nullptr;
        if(left == right) return lists[left];

        //求中点,获取左右区间 [left,mid] [mid+1,right]
        int mid = (right + left) / 2;
        //合并左子区间中的链表
        ListNode* lefthead = merge(lists,left,mid);
        //合并右子区间中的链表
        ListNode* righthead = merge(lists,mid+1,right);
        //合并当前左右链表:升序
        return mergeList(lefthead,righthead);
    }

    ListNode* mergeList(ListNode* l1, ListNode* l2)
    {
        if(l1 == nullptr) return l2;
        if(l2 == nullptr) return l1;

        ListNode* head = new ListNode(0);
        ListNode* tail = head;
        while(l1 && l2)
        {
            if(l1->val < l2->val)
            {
                tail->next = l1;
                tail = tail->next;
                l1 = l1->next;
            }
            else
            {
                tail->next = l2;
                tail = tail->next;
                l2 = l2->next;
            }
        }

        //处理剩余的链表
        while(l1)
        {
            tail->next = l1;
            tail = tail->next;
            l1 = l1->next;
        }

        while(l2)
        {
            tail->next = l2;
            tail = tail->next;
            l2 = l2->next;
        }

        ListNode* next = head->next;
        delete head;
        return next;
    }

    ListNode* mergeKLists(vector<ListNode*>& lists) {
        return merge(lists,0,lists.size()-1);
    }
};

  
  
  
  
  
  
  

6、K个一组翻转链表(hard)

  题源:链接

在这里插入图片描述
  
  

6.1、题解

  1)、思路分析
  1、遍历一遍链表,求出链表总结点数目
  2、根据结点总数分组,获得需要翻转的轮次count
  3、进行count次的翻转(可用头插、可用三指针法等等)

在这里插入图片描述

  
  2)、题解

/**
 * 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* reverseKGroup(ListNode* head, int k) {
        //遍历求链表总节点数
        int n = 0;
        ListNode* cur = head;
        while(cur)
        {
            cur = cur->next;
            n++;
        }
        //获取需要翻转的轮次
        int round = n / k;

        //翻转round轮,每次翻转k个节点
        ListNode* newhead = new ListNode;//哨兵位的头结点
        ListNode* mark = newhead;//用于标记每组头插的起始位置
        cur = head;
        for(int i = 0; i < round; ++i)
        {
            ListNode* tail =  cur;//用于记录当前回合的尾结点(实则是还未逆序前的首节点)
            for(int j = 0; j < k; ++j)
            {
                //头插
                ListNode* next = cur->next;//记录下一个节点
                cur->next = mark->next;//更改链接关系
                mark->next = cur;
                cur = next;//下一个节点
            }
            mark = tail;
        }
        if(cur)//说明原链表中还有残余节点,把不需要翻转的接上
            mark->next = cur;
        
        head = newhead->next;
        delete newhead;
        return head;
    }
};

  
  
  
  
  
  
  
  
  
  
  
  
  

Fin、共勉。

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值