链表:操作

LeetCode707. 设计链表

https://leetcode-cn.com/problems/design-linked-list/

设计链表的实现。您可以选择使用单链表或双链表。单链表中的节点应该具有两个属性:valnextval 是当前节点的值,next 是指向下一个节点的指针/引用。如果要使用双向链表,则还需要一个属性 prev 以指示链表中的上一个节点。假设链表中的所有节点都是 0-index 的。

在链表类中实现这些功能:

  • get(index):获取链表中第 index 个节点的值。如果索引无效,则返回-1
  • addAtHead(val):在链表的第一个元素之前添加一个值为 val 的节点。插入后,新节点将成为链表的第一个节点。
  • addAtTail(val):将值为 val 的节点追加到链表的最后一个元素。
  • addAtIndex(index,val):在链表中的第 index 个节点之前添加值为 val 的节点。如果 index 等于链表的长度,则该节点将附加到链表的末尾。如果 index 大于链表长度,则不会插入节点。如果index小于0,则在头部插入节点。
  • deleteAtIndex(index):如果索引 index 有效,则删除链表中的第 index 个节点。
MyLinkedList linkedList = new MyLinkedList();
linkedList.addAtHead(1);
linkedList.addAtTail(3);
linkedList.addAtIndex(1,2);   //链表变为1-> 2-> 3
linkedList.get(1);            //返回2
linkedList.deleteAtIndex(1);  //现在链表是1-> 3
linkedList.get(1);            //返回3
思路

设置一个虚拟头结点再进行操作。具体思路见代码和注释。

代码
class MyLinkedList 
{
public:
    struct LinkedNode
    {
        int val;
        LinkedNode* next;
        LinkedNode() : val(0), next(nullptr) {}
        LinkedNode(int val) : val(val), next(nullptr) {}
        LinkedNode(int val, LinkedNode* next) : val(val), next(next){}
    };

    /** Initialize your data structure here. */
    MyLinkedList() 
    {
        sz = 0;
        dummy = new LinkedNode();
    }
    
    /** Get the value of the index-th node in the linked list. If the index is invalid, return -1. */
    int get(int index) 
    {
        if (index < 0 || index > (sz - 1))
        {
            return -1;
        }

        LinkedNode* cur = dummy->next;
        while (index--)
        {
            cur = cur->next;
        }

        return cur->val;
    }
    
    /** Add a node of value val before the first element of the linked list. After the insertion, the new node will be the first node of the linked list. */
    void addAtHead(int val) 
    {
        LinkedNode* newNode = new LinkedNode(val);
        newNode->next = dummy->next;
        dummy->next = newNode;
        ++sz;
    }
    
    /** Append a node of value val to the last element of the linked list. */
    void addAtTail(int val) 
    {
        LinkedNode* newNode = new LinkedNode(val);
        LinkedNode* cur = dummy;
        while (cur->next)
        {
            cur = cur->next;
        }
        newNode->next = cur->next;
        cur->next = newNode;
        ++sz;
    }
    
    /** Add a node of value val before the index-th node in the linked list. If index equals to the length of linked list, the node will be appended to the end of linked list. If index is greater than the length, the node will not be inserted. */
    void addAtIndex(int index, int val) 
    {
        if (index > sz)
        {
            return;
        }

        LinkedNode* newNode = new LinkedNode(val);
        LinkedNode* cur = dummy;
        while (index--)
        {
            cur = cur->next;
        }
        newNode->next = cur->next;
        cur->next = newNode;
        ++sz;
    }
    
    /** Delete the index-th node in the linked list, if the index is valid. */
    void deleteAtIndex(int index) 
    {
        if (index < 0 || index > (sz - 1))
        {
            return;
        }

        LinkedNode* cur = dummy;
        while(index--)
        {
            cur = cur->next;
        }
        LinkedNode* temp = cur->next;
        cur->next = cur->next->next;
        delete temp;
        --sz;
    }

private:
    int sz;
    LinkedNode* dummy;
};

/**
 * Your MyLinkedList object will be instantiated and called as such:
 * MyLinkedList* obj = new MyLinkedList();
 * int param_1 = obj->get(index);
 * obj->addAtHead(val);
 * obj->addAtTail(val);
 * obj->addAtIndex(index,val);
 * obj->deleteAtIndex(index);
 */

LeetCode203. 移除链表元素

https://leetcode-cn.com/problems/remove-linked-list-elements/

给你一个链表的头节点 head 和一个整数 val ,请你删除链表中所有满足 Node.val == val 的节点,并返回 新的头节点

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-ZysF0rSM-1617461832513)(D:\C++服务器开发\算法题\LeetCode题解\图解\移除链表元素.jpg)]

输入:head = [1,2,6,3,4,5,6], val = 6
输出:[1,2,3,4,5]
思路

设置一个虚拟头结点再进行操作。具体思路见代码和注释。

代码
/**
 * 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* removeElements(ListNode* head, int val) 
    {
        ListNode* dummy = new ListNode();
        dummy->next = head;

        ListNode* cur = dummy;
        while (cur->next)
        {
            if (cur->next->val == val)
            {
                ListNode* temp = cur->next;
                cur->next = cur->next->next;
                delete temp;
            }
            else 
            {
                cur = cur->next;
            }
        }

        ListNode* result = dummy->next;
        delete dummy;
        return result;
    }
};

LeetCode206. 反转链表

https://leetcode-cn.com/problems/reverse-linked-list/

反转一个单链表。

输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL

进阶:
你可以迭代或递归地反转链表。你能否用两种方法解决这道题?

思路

首先定义一个cur指针,指向头结点,再定义一个pre指针,初始化为null。

然后就要开始反转了:

  • 把 cur->next 节点用tmp指针保存一下
  • 为什么要保存一下这个节点呢,因为接下来要改变 cur->next 的指向了,将cur->next 指向pre ,此时已经反转了第一个节点了。
  • 继续移动pre和cur指针。最后,cur 指针已经指向了null,循环结束,链表也反转完毕了。此时返回pre指针就可以了,因为pre指针就指向了新的头结点。

图片

代码
/**
 * 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) 
    {
        ListNode* temp;
        ListNode* pre = nullptr;
        ListNode* cur = head;
        while (cur)
        {
            temp = cur->next;
            cur->next = pre;
            pre = cur;
            cur = temp;
        }

        return pre;
    }*/

    //递归
    ListNode* reverse(ListNode* pre, ListNode* cur)
    {
        if (!cur) return pre;

        ListNode* temp = cur->next;
        cur->next = pre;
        return reverse(cur, temp);
    }
    
    ListNode* reverseList(ListNode* head)
    {
        return reverse(nullptr, head);
    }
};

LeetCode24. 两两交换链表中的节点

https://leetcode-cn.com/problems/swap-nodes-in-pairs/

给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。

你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换

在这里插入图片描述

输入:head = [1,2,3,4]
输出:[2,1,4,3]
思路

设置一个虚拟头结点再进行操作。具体思路见代码和注释。

代码
/**
 * 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) 
    {
        ListNode* dummy = new ListNode();
        dummy->next = head;

        ListNode* cur = dummy;
        while (head && head->next)
        {
            ListNode* first = head;
            ListNode* second = head->next;

            cur->next = second;
            first->next = second->next;
            second->next = first;

            cur = first;
            head = first->next;
        }

        ListNode* result = dummy->next;
        delete dummy;
        return result;
    }
};

LeetCode25. K个一组翻转链表

https://leetcode-cn.com/problems/reverse-nodes-in-k-group/

给你一个链表,每 k 个节点一组进行翻转,请你返回翻转后的链表。

k 是一个正整数,它的值小于或等于链表的长度。

如果节点总数不是 k 的整数倍,那么请将最后剩余的节点保持原有顺序。

进阶:

你可以设计一个只使用常数额外空间的算法来解决此问题吗?
你不能只是单纯的改变节点内部的值,而是需要实际进行节点交换。

在这里插入图片描述

输入:head = [1,2,3,4,5], k = 3
输出:[3,2,1,4,5]
思路
  • 设置一个虚拟头结点dummy

  • 设置两个变量pre和right,pre指向每次要翻转的链表的头结点的上一个节点,right指向每次要翻转的链表的尾节点

  • 循环k次,找到待翻转的链表的尾节点,注意:记录待翻转链表的后继,防止断链;设置变量left指向每次要翻转的链表的头节点;翻转链表

  • 重置 pre和right指针,然后进入下一次循环

代码
/**
 * 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 
{
private:
    ListNode* reverseList(ListNode* head) 
    {
        ListNode* temp;
        ListNode* pre = nullptr;
        ListNode* cur = head;
        while (cur)
        {
            temp = cur->next;
            cur->next = pre;
            pre = cur;
            cur = temp;
        }

        return pre;
    }

public:
    ListNode* reverseKGroup(ListNode* head, int k) 
    {
        ListNode* dummy = new ListNode();
        dummy->next = head;

        //pre指向每次要翻转的链表的头结点的上一个节点,right指向每次要翻转的链表的尾节点
        ListNode* pre = dummy;
        ListNode* right = dummy;

        while (right->next)
        {
            //循环k次,找到要翻转的链表的尾节点
            for (int i = 0; i < k && right; ++i)
            {
                right = right->next;
            }
            //如果right==null,那么需要翻转的链表的节点数小于k,不执行翻转。
            if (!right) break;

            //记录待翻转链表的后继,防止断链
            ListNode* temp = right->next;
            //断链
            right->next = nullptr;

            //left指向每次要翻转的链表的头节点
            ListNode* left = pre->next;

            //翻转链表
            pre->next = reverseList(left);
            
            //重新链接链表
            left->next = temp;

            //将pre指向下次要翻转的链表的头结点的上一个节点。即left
            pre = left;
            //将end置为下次要翻转的链表的头结点的上一个节点。即left
            right = left;
        }

        ListNode* result = dummy->next;
        delete dummy;
        return result;
    }
};

LeetCode141. 环形链表

https://leetcode-cn.com/problems/linked-list-cycle/

给定一个链表,判断链表中是否有环。

如果链表中有某个节点,可以通过连续跟踪 next 指针再次到达,则链表中存在环。 为了表示给定链表中的环,我们使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。 如果 pos 是 -1,则在该链表中没有环。注意:pos 不作为参数进行传递,仅仅是为了标识链表的实际情况。

如果链表中存在环,则返回 true 。 否则,返回 false 。

在这里插入图片描述

输入:head = [3,2,0,-4], pos = 1
输出:true
解释:链表中有一个环,其尾部连接到第二个节点。
思路

使用快慢指针法。

分别定义 fast 和 slow指针,从头结点出发,fast指针每次移动两个节点,slow指针每次移动一个节点,如果 fast 和 slow指针在途中相遇 ,说明这个链表有环。

代码
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */

class Solution 
{
public:
    bool hasCycle(ListNode *head) 
    {
        ListNode* slow = head;
        ListNode* fast = head;
        while (fast && fast->next)
        {
            slow = slow->next;
            fast = fast->next->next;
            if (slow == fast)
            {
                return true;
            }
        }
        return false;
    }
};

LeetCode142. 环形链表II

https://leetcode-cn.com/problems/linked-list-cycle-ii/

给定一个链表,返回链表开始入环的第一个节点。 如果链表无环,则返回 null。

为了表示给定链表中的环,我们使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。 如果 pos 是 -1,则在该链表中没有环。注意,pos 仅仅是用于标识环的情况,并不会作为参数传递到函数中。

说明:不允许修改给定的链表。

在这里插入图片描述

输入:head = [3,2,0,-4], pos = 1
输出:返回索引为 1 的链表节点
解释:链表中有一个环,其尾部连接到第二个节点。
思路

使用快慢指针法。

分别定义 fast 和 slow指针,从头结点出发,fast指针每次移动两个节点,slow指针每次移动一个节点

假设从头结点到环形入口节点 的节点数为x。环形入口节点到 fast指针与slow指针相遇节点 节点数为y。从相遇节点到环形入口节点节点数为 z。如图所示:

图片

那么相遇时:slow指针走过的节点数为: x + y, fast指针走过的节点数:x + y + n (y + z),n为fast指针在环内走了n圈才遇到slow指针。

不妨假设n = 1。因为fast指针是一步走两个节点,slow指针一步走一个节点, 所以 fast指针走过的节点数 = slow指针走过的节点数 * 2:x + y + y + z = (x + y) * 2,化简:x = z

这就意味着:从头结点出发一个指针,从相遇节点同时出发一个指针,这两个指针每次只走一个节点, 那么当这两个指针相遇的时候就是 环形入口的节点

代码
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution 
{
public:
    ListNode *detectCycle(ListNode *head) 
    {
        ListNode* slow = head;
        ListNode* fast = head;
        while (fast && fast->next)
        {
            slow = slow->next;
            fast = fast->next->next;

            if (slow == fast)
            {
                ListNode* index1 = head;
                ListNode* index2 = fast;
                while (index1 != index2)
                {
                    index1 = index1->next;
                    index2 = index2->next;
                }
                return index2;
            }
        }
        return nullptr;
    }
};

LeetCode21. 合并两个有序链表

https://leetcode-cn.com/problems/merge-two-sorted-lists/

将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。

在这里插入图片描述

输入:l1 = [1,2,4], l2 = [1,3,4]
输出:[1,1,2,3,4,4]

思路(迭代)

设置一个虚拟头结点再进行操作。

设置一个工作指针cur,初始指向虚拟头节点,我们需要做的是调整它的 next 指针。然后,我们重复以下过程,直到 l1 或者 l2 指向了 nullptr :如果 l1 当前节点的值小于等于 l2 ,我们就把cur指向l1当前节点同时将 l1 指针往后移一位;否则,我们对 l2 做同样的操作。接着将cur后移一位。

在循环终止的时候, l1l2 至多有一个是非空的。由于输入的两个链表都是有序的,所以不管哪个链表是非空的,它包含的所有元素都比前面已经合并链表中的所有元素都要大,所以我们只需要cur指向非空链表并返回合并链表即可。

代码
/**
 * 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* mergeTwoLists(ListNode* l1, ListNode* l2) 
    {
        ListNode* dummy = new ListNode();
        ListNode* cur = dummy;
        while (l1 && l2)
        {
            if (l1->val < l2->val)
            {
                cur->next = l1;
                l1 = l1->next;
            }
            else
            {
                cur->next = l2;
                l2 = l2->next;
            }
            cur = cur->next;
        }

        if (l1)
        {
            cur->next = l1;
        }
        if (l2)
        {
            cur->next = l2;        
        }

        ListNode* result = dummy->next;
        delete dummy;
        return result;
    }
}
思路(递归)

img

img

img

img

img

img

img

img

代码
/**
 * 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* mergeTwoLists(ListNode* l1, ListNode* l2) 
    {
        if (!l1)
        {
            return l2;
        }
        else if (!l2)
        {
            return l1;
        }
        else if (l1->val < l2->val)
        {
            l1->next = mergeTwoLists(l1->next, l2);
            return l1;
        }
        else
        {
            l2->next = mergeTwoLists(l1, l2->next);
            return l2;
        }
    }
};

LeetCode23. 合并K个升序链表

https://leetcode-cn.com/problems/merge-k-sorted-lists/

给你一个链表数组,每个链表都已经按升序排列。

请你将所有链表合并到一个升序链表中,返回合并后的链表。

输入:lists = [[1,4,5],[1,3,4],[2,6]]
输出:[1,1,2,3,4,4,5,6]
解释:链表数组如下:
[
  1->4->5,
  1->3->4,
  2->6
]
将它们合并到一个有序链表中得到。
1->1->2->3->4->4->5->6

思路(比较K个节点求最小值)

采用一种办法,比较当前每个链表没有被合并的元素的最前面一个(k个链表就最多有 k个满足这样条件的元素),每次在这些元素里面选取 val 最小的元素合并到答案中。

  • 顺序比较
  • 采用优先队列辅助比较

假设有K个链表,所有链表的总节点数为N。

  • 顺序比较:每次O(K)比较 K个节点求最小值, 时间复杂度:O(NK)
  • 采用优先队列辅助比较:每次O(logK)比较 K个节点求最小值, 时间复杂度:O(NlogK)
代码
/**
 * 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:
    //每次顺序比较K个节点求最小值
    /*ListNode* mergeKLists(vector<ListNode*>& lists) 
    {
        int k = lists.size();

        ListNode* dummy = new ListNode();
        ListNode* cur = dummy;
        while (1)
        {
            ListNode* minNode = nullptr;
            int minNum = -1;
            for (int i = 0; i < k; ++i)
            {

                if (!lists[i])
                {
                    continue;
                }
                if (!minNode || lists[i]->val < minNode->val)
                {
                    minNode = lists[i];
                    minNum = i;
                }
            }
            if (!minNode) break;

            cur->next = lists[minNum];
            lists[minNum] = lists[minNum]->next;
            cur = cur->next;
        }

        ListNode* result = dummy->next;
        delete dummy;
        return result;
    }*/

    //使用小根堆对进行优化,每次O(logK)比较 K个节点求最小值
    struct cmp
    {
        bool operator()(ListNode* a, ListNode* b)
        {
            return a->val > b->val;
        }
    };
    ListNode* mergeKLists(vector<ListNode*>& lists) 
    {
        priority_queue<ListNode*, vector<ListNode*>, cmp> pri_que;
        for (const auto& list : lists)
        {
            if (list)
            {
                pri_que.push(list);
            }
        }

        ListNode* dummy = new ListNode();
        ListNode* cur = dummy;
        while(!pri_que.empty())
        {
            ListNode* node = pri_que.top();
            pri_que.pop();
            cur->next = node;
            node = node->next;
            cur = cur->next;
            if (node) 
            {
                pri_que.push(node);
            }
        }

        return dummy->next;
    }
}

思路(两两合并链表)

首先要用到的一个基本操作就是LeetCode21. 合并两个有序链表中实现的操作。有两种两两合并的方式:

  • 逐一合并

  • 分治合并:

    • k个链表两两配对,进行第一轮合并,结束后k个链表被合并成k/2个链表

    • k/2个链表依然两两配对,进行第二轮合并,结束后k/2个链表被合并成k/4个链表

    • 重复上述过程,进行log(k)次合并,完成总体合并工作

      分治合并

假设有K个链表,所有链表的总节点数为N。

  • 逐一合并:时间复杂度为O (NK)
  • 分治合并:时间复杂度为O(NlogK)
代码
/**
 * 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 
{
private:
    ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) 
    {
        ListNode* dummy = new ListNode();
        ListNode* cur = dummy;
        while (l1 && l2)
        {
            if (l1->val < l2->val)
            {
                cur->next = l1;
                l1 = l1->next;
            }
            else
            {
                cur->next = l2;
                l2 = l2->next;
            }
            cur = cur->next;
        }

        if (l1)
        {
            cur->next = l1;
        }
        if (l2)
        {
            cur->next = l2;        
        }

        ListNode* result = dummy->next;
        delete dummy;
        return result;
    }
    
public:
    //逐一合并
    /*ListNode* mergeKLists(vector<ListNode*>& lists)
    {
        int k = lists.size();
        if (k == 0) return nullptr;

        ListNode* head = lists[0];
        for (int i = 1; i < k; ++i)
        {
            if (lists[i])
            {
                head = mergeTwoLists(head, lists[i]);
            }
        }

        return head;
    }*/

    //分治合并
    ListNode* mergeKListsHelper(vector<ListNode*>& lists, int left, int right)
    {
        if (left == right) return lists[left];

        int mid = left + (right - left) / 2;
        ListNode* l1 = mergeKListsHelper(lists, left, mid);
        ListNode* l2 = mergeKListsHelper(lists, mid + 1, right);
        return mergeTwoLists(l1, l2);
    }
    ListNode* mergeKLists(vector<ListNode*>& lists)
    {
        int k = lists.size();
        if (k == 0) return nullptr;

        return mergeKListsHelper(lists, 0, k - 1);
    }

};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值