前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >算法:链表

算法:链表

作者头像
用户3578099
发布2022-03-15 08:03:52
4210
发布2022-03-15 08:03:52
举报
文章被收录于专栏:AI科技时讯

链表的题目一定要画出来,然后理清前后顺序关系,一般解法是遍历,快慢指针,二分查找等;

例题

移除链表元素

给你一个链表的头节点 head 和一个整数 val ,请你删除链表中所有满足 Node.val == val 的节点,并返回 新的头节点 。遍历即可,原地删除方法是当cur.next==val时候cur.next = cur.next.next, 注意头部是否可以增添一个空的,便于比较第一个节点。

•python

代码语言:javascript
复制
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next


class Solution:
    def removeElements(self, head: ListNode, val: int) -> ListNode:
        head = ListNode(next=head)
        cur = head
        while cur.next:
            if cur.next.val == val:
                cur.next = cur.next.next  # remove cur.next 此时并不需要变更此时的cur,因为还需要继续判断接下来的数字
            else:
                cur = cur.next
        return head.next

•c++

代码语言:javascript
复制
/**
 * 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) {
        struct ListNode* dummyHead = new ListNode(0, head);
        dummyHead -> next = head;
        struct ListNode* cur = dummyHead;
        while(cur->next != NULL)
        {
            if(cur->next->val == val)
            {
                cur->next = cur->next->next;
            }
            else
            {
                cur = cur->next;
            }
        }
        return dummyHead->next;
        delete dummyHead;
    }
};

旋转链表

给你一个链表的头节点 head ,旋转链表,将链表每个节点向右移动 k 个位置。

示例 1:输入:head = [1,2,3,4,5], k = 2 输出:[4,5,1,2,3]

类似这种旋转链表的问题,可以先将单链表变成循环链表,尾部节点的下一个节点是头节点,再判断需要走几步,断掉,就变成旋转链表了。难点确定走几步:

•首先遍历整个单链表获得长度;•再使用k对长度取模,判断余数,余数就是要往右走的步数•但是确定头节点的位置为 链表长度-走的步数 才是真实要走的步数

python

代码语言:javascript
复制
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def rotateRight(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:
        if k==0 or not head or not head.next:
            return head
        length = 0
        temp = head
        # 获得长度,注意最后一个节点没有算进去
        while temp.next:
            length += 1
            temp = temp.next

        # 最后一个节点与第一个节点串起来
        temp.next = head

        # 判断需要走的步长
        k = k % (length+1)  # length+1才是真实长度


        temp = head
        for i in range(length-k):
            temp = temp.next
        head = temp.next  # 断开后 后面的节点成为首节点
        temp.next = None
        return head

c++

代码语言:javascript
复制
/**
 * 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* rotateRight(ListNode* head, int k) {
        if (k == 0 || head == nullptr || head->next == nullptr) {
            return head;
        }
        int n = 1;  // 起始为1
        ListNode* iter = head;
        while (iter->next != nullptr) {
            iter = iter->next;
            n++;
        }
        int add = n - k % n;
        if (add == n) {
            return head;
        }
        iter->next = head;
        while (add--) {
            iter = iter->next;
        }
        ListNode* ret = iter->next;
        iter->next = nullptr;
        return ret;
    }
};
合并两个有序列表

将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。示例 1:输入:l1 = [1,2,4], l2 = [1,3,4] 输出:[1,1,2,3,4,4]

两个指针互相进行比较,如果值大就继续,直到有一个指针到末尾之后,再拼接剩余的链表。或者用递归的方法,只比较第一个元素,剩余的元素又跟原始问题一样。

递归法

•python

代码语言:javascript
复制
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next

class Solution:
    def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:
        if list1 is None:
            return list2
        elif list2 is None:
            return list1

        elif list1.val <= list2.val:
            list1.next = self.mergeTwoLists(list1.next, list2)
            return list1
        else:
            list2.next = self.mergeTwoLists(list1, list2.next)
            return list2

•c++

代码语言:javascript
复制
/**
 * 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* list1, ListNode* list2) {
        if(list1 == nullptr)
        {
            return list2;
        }
        else if(list2 == nullptr)
        {
            return list1;
        }

        else if(list1 -> val <= list2->val)
        {
            list1->next = mergeTwoLists(list1->next, list2);
            return list1;
        }

        else
        {
            list2->next = mergeTwoLists(list1, list2->next);
            return list2;
        }
    }
};

迭代遍历 先定义一个哨兵,然后逐个比较,将小的添加到哨兵后面,以及备份一个哨兵,当第一个哨兵遍历完成后,备份哨兵的下一个就是头节点。

•python

代码语言:javascript
复制
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:
        prehead = ListNode(-1)
        prev = prehead
        while list1 and list2:
            if list1.val <= list2.val:
                prev.next = list1
                list1 = list1.next
            else:
                prev.next = list2
                list2 = list2.next
            prev = prev.next
        prev.next = list1 if list1 else list2
        return prehead.next

•cpp

代码语言:javascript
复制
/**
 * 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* list1, ListNode* list2) {
        ListNode* prehead = new ListNode(-1);
        ListNode* prev = prehead;
        while(list1 != nullptr and list2 != nullptr)
        {
            if(list1->val <= list2->val)
            {
                prev->next = list1;
                list1 = list1->next;
            }
            else
            {
                prev->next = list2;
                list2 = list2->next;
            }
            prev = prev->next;
        }

        prev->next = list1 != nullptr? list1 : list2;
        return prehead->next;

    }
};

相交链表

给你两个单链表的头节点 headA 和 headB ,请你找出并返回两个单链表相交的起始节点。如果两个链表不存在相交节点,返回 null 。

图示两个链表在节点 c1 开始相交:

在这里插入图片描述

题目数据 保证 整个链式结构中不存在环。

注意,函数返回结果后,链表必须 保持其原始结构 。

自定义评测:

评测系统 的输入如下(你设计的程序 不适用 此输入):

•intersectVal - 相交的起始节点的值。如果不存在相交节点,这一值为 0•listA - 第一个链表•listB - 第二个链表•skipA - 在 listA 中(从头节点开始)跳到交叉节点的节点数•skipB - 在 listB 中(从头节点开始)跳到交叉节点的节点数•评测系统将根据这些输入创建链式数据结构,并将两个头节点 headA 和 headB 传递给你的程序。如果程序能够正确返回相交节点,那么你的解决方案将被 视作正确答案 。•输入:intersectVal = 8, listA = [4,1,8,4,5], listB = [5,6,1,8,4,5], skipA = 2, skipB = 3•输出:Intersected at '8'•解释:相交节点的值为 8 (注意,如果两个链表相交则不能为 0)。从各自的表头开始算起,链表 A 为 [4,1,8,4,5],链表 B 为 [5,6,1,8,4,5]。在 A 中,相交节点前有 2 个节点;在 B 中,相交节点前有 3 个节点。

哈希表方法,遍历A,存储成哈希表,key为节点。遍历B,每个节点去哈希表中找是否有存在的点,如果存在,表明有相交的节点,如果不存在,则没有相交的节点

•python

代码语言:javascript
复制
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode:
        if not headA or not headB:
            return None

        s = set()
        p = headA
        while p:
            s.add(p)
            p = p.next

        q = headB
        while q:
            if q in s:
                return q
            q = q.next
        return None

•c++

代码语言:javascript
复制
/**
 * 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) {
        unordered_set<ListNode *> s;
        for(ListNode* p=headA; p!=nullptr; p=p->next)
        {
            s.emplace(p);
        }
        for(ListNode* q=headB; q!=nullptr; q=q->next)
        {
            if(s.find(q) != s.end())
            {
                return q;
            }
        }
        return nullptr;
    }
};

双指针法

考虑构建两个节点指针 A , B 分别指向两链表头节点 headA , headB ,做如下操作:

•指针 A 先遍历完链表 headA ,再开始遍历链表 headB ,当走到 node 时,共走步数为:

a + (b - c)

•指针 B 先遍历完链表 headB ,再开始遍历链表 headA ,当走到 node 时,共走步数为:

b + (a - c)

如下式所示,此时指针 A , B 重合,并有两种情况:

a+(b−c)=b+(a−c)

•若两链表 有 公共尾部 (即 c > 0c = 0) :指针 A , B 同时指向 null•python

代码语言:javascript
复制
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode:
        A, B = headA, headB
        while A != B:
            A = A.next if A else headB
            B = B.next if B else headA
        return A

•c++

代码语言:javascript
复制
/**
 * 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) {
        ListNode* A = headA;
        ListNode* B = headB;
        while(A != B)
        {
            A = A != nullptr ? A->next : headB;
            B = B != nullptr ? B->next: headA;
        }
        return A;
    }
};
删除排序链表中的重复元素 II

给定一个已排序的链表的头 head , 删除原始链表中所有重复数字的节点,只留下不同的数字 。返回 已排序的链表 。示例 1:

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

由于是排序数组,要利用好,如果存在重复元素,则两个元素肯定是挨着的,但是第一个元素也需要进行处理,这种情况一般是定义一个哨兵,放在头节点的前面。判断是否有重复元素的条件cur.next == cur.next.next, 另外还要保存该重复值,这样能对删除后的后面也能进行删除

•python

代码语言:javascript
复制
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def deleteDuplicates(self, head: ListNode) -> ListNode:
        if not head:
            return head

        dummyHead = ListNode(0, head)
        cur = dummyHead
        while cur.next and cur.next.next:
            if cur.next.val == cur.next.next.val:
                x = cur.next.val
                while cur.next and cur.next.val == x:
                    cur.next = cur.next.next
            else:
                cur = cur.next
        return dummyHead.next

•c++

代码语言:javascript
复制
/**
 * 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* deleteDuplicates(ListNode* head) {
        if(head == nullptr || head->next==nullptr)
        {
            return head;
        }
        ListNode* dummyHead = new ListNode(0, head);
        ListNode* cur = dummyHead;

        while(cur->next && cur->next->next)
        {
            if(cur->next->val == cur->next->next->val)
            {
                int x = cur->next->val;
                while(cur->next && cur->next->val==x)
                {
                    cur->next = cur->next->next;
                }
            }
            else
            {
                cur = cur->next;
            }
        }

        return dummyHead->next;
    }
};
本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2022-02-21,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 AI科技时讯 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 例题
    • 移除链表元素
    • 旋转链表
      • 合并两个有序列表
      • 相交链表
        • 删除排序链表中的重复元素 II
        领券
        问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档