【leetcode刷题总结】——代码随想录(链表总结)

代码随想录按照数组-> 链表-> 哈希表->字符串->栈与队列->树->回溯->贪心->动态规划->图论->高级数据结构,再从简单刷起,做了几个类型题目之后,再慢慢做中等题目、困难题目。

以下是个人刷题总结,官方网站 https://programmercarl.com/

代码链接:Leetcode-Python: Leetcode-Python

目录

链表理论基础

203.移除链表元素

707.设计链表

206.反转链表

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

19.删除链表的倒数第N个节点

160. 链表相交

142.环形链表II

总结


链表理论基础

什么是链表,链表是一种通过指针串联在一起的线性结构,每一个节点由两部分组成,一个是数据域一个是指针域(存放指向下一个节点的指针),最后一个节点的指针域指向null(空指针的意思)。

链表的入口节点称为链表的头结点也就是head。

单链表

数组是在内存中是连续分布的,但是链表在内存中可不是连续分布的。

链表是通过指针域的指针链接在内存中各个节点。

所以链表中的节点在内存中不是连续分布的 ,而是散乱分布在内存中的某地址上,分配机制取决于操作系统的内存管理。

双链表

双链表:每一个节点有两个指针域,一个指向下一个节点,一个指向上一个节点。

双链表 既可以向前查询也可以向后查询。

循环链表

循环链表,顾名思义,就是链表首尾相连。

循环链表可以用来解决约瑟夫环问题。

链表的定义

class ListNode:
    def __init__(self, val, next=None):
        self.val = val
        self.next = next

203.移除链表元素

力扣题目链接(opens new window)

题意:删除链表中等于给定值 val 的所有节点。

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

示例 2: 输入:head = [], val = 1 输出:[]

示例 3: 输入:head = [7,7,7,7], val = 7 输出:[]

这里添加虚拟节点的方法

class Solution(object):
    def removeElements(self, head, val):
        """
        :type head: ListNode
        :type val: int
        :rtype: ListNode
        """
        # 添加虚拟节点
        dummy_head = ListNode(next=head)
        cur = dummy_head
        while cur.next is not None:
            # 判断要删除的节点
            if cur.next.val == val:
                cur.next = cur.next.next
            else:
                cur = cur.next
            return dummy_head.next

非常简单。最后要返回dummy_head.next。

707.设计链表

力扣题目链接(opens new window)

题意:

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

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

这题有点长、可以进行拆分。

这道题目设计链表的五个接口:

  • 获取链表第index个节点的数值
  • 在链表的最前面插入一个节点
  • 在链表的最后面插入一个节点
  • 在链表第index个节点前面插入一个节点
  • 删除链表的第index个节点

可以说这五个接口,已经覆盖了链表的常见操作,是练习链表操作非常好的一道题目

class MyLinkedList(object):

    def __init__(self):
        self.head = Node()
        self.size = 0  # 设置一个链表长度的属性,便于后续操作,注意每次增和删的时候都要更新

    def get(self, index):
        """
        :type index: int
        :rtype: int
        """
        if index < 0 or index >= self.size:
            return -1
        cur = self.head.next
        while index:
            cur = cur.next
            index -= 1
        return cur.val

    def addAtHead(self, val):
        """
        :type val: int
        :rtype: None
        """
        # 新建新节点,将值置为val
        new_node = Node(val)
        # 头插法
        new_node.next = self.head.next
        self.head.next = new_node
        self.size += 1

    def addAtTail(self, val):
        """
        :type val: int
        :rtype: None
        """
        new_node = Node(val)
        cur = self.head
        # 只要链表的next不为空,遍历到最后的位置
        while cur.next:
            cur = cur.next
        # 在最后的位置插入元素 尾插法
        cur.next = new_node
        # 添加成功 链表长度+1
        self.size += 1

    def addAtIndex(self, index, val):
        """
        :type index: int
        :type val: int
        :rtype: None
        在指定位置添加链表元素
        """
        # 如果index<0 选择头插法
        if index < 0:
            self.addAtHead(val)
            return
        # 尾插法
        elif index == self.size:
            self.addAtTail(val)
            return
        # 不存在
        elif index > self.size:
            return

        node = Node(val)
        pre = self.head
        while index:
            pre = pre.next
            index -= 1
        node.next = pre.next
        pre.next = node
        self.size += 1

    def deleteAtIndex(self, index):
        """
        :type index: int
        :rtype: None
        """
        if index < 0 or index >= self.size:
            return
        pre = self.head
        while index:
            pre = pre.next
            index -= 1
        pre.next = pre.next.next
        self.size -= 1

206.反转链表

力扣题目链接(opens new window)

题意:反转一个单链表。

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

#思路

如果再定义一个新的链表,实现链表元素的反转,其实这是对内存空间的浪费

其实只需要改变链表的next指针的指向,直接将链表反转 ,而不用重新定义一个新的链表,如图所示:

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

然后就要开始反转了,首先要把 cur->next 节点用tmp指针保存一下,也就是保存一下这个节点。

为什么要保存一下这个节点呢,因为接下来要改变 cur->next 的指向了,将cur->next 指向pre ,此时已经反转了第一个节点了。

接下来,就是循环走如下代码逻辑了,继续移动pre和cur指针。

最后,cur 指针已经指向了null,循环结束,链表也反转完毕了。 此时我们return pre指针就可以了,pre指针就指向了新的头结点。


# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution(object):
    def reverseList(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        # 申请两个指针,第一个指针叫 pre,最初是指向 null 的。
        pre = None
        # 第二个指针 cur 指向 head,然后不断遍历 cur
        cur = head
        # 每次迭代到 cur,都将 cur 的 next 指向 pre,然后 pre 和 cur 前进一位。
        while cur is not None:
            # 记录当前节点的下一个节点
            tmp = cur.next
            # 当前节点指向pre
            cur.next = pre
            # pre和cur节点都前进一位
            pre = cur
            cur = tmp
        return pre

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

力扣题目链接(opens new window)

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

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

class Solution(object):
    def swapPairs(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        if not head or not head.next:
            return head
        # 初始时,cur指向虚拟头结点
        newHead = head.next
        head.next = self.swapPairs(newHead.next)
        newHead.next = head
        return newHead

# 时间复杂度:O(n)
# 空间复杂度:O(1)

19.删除链表的倒数第N个节点

力扣题目链接(opens new window)

给你一个链表,删除链表的倒数第 n 个结点,并且返回链表的头结点。

进阶:你能尝试使用一趟扫描实现吗?

class Solution(object):
    def removeNthFromEnd(self, head, n):
        """
        :type head: ListNode
        :type n: int
        :rtype: ListNode
        """
        # 保存链表的长度
        len = 0
        cur = head
        while cur:  # 求链表的长度
            cur = cur.next
            len += 1

        # 添加虚拟节点
        dummy_head = ListNode(next=head)
        cur = dummy_head
        delect = 0
        while cur.next is not None:
            delect += 1
            # 判断要删除的节点
            if delect == len - n:
                cur.next = cur.next.next
            else:
                cur = cur.next
            return dummy_head.next


if __name__ == '__main__':
    sol = Solution()
    head = None
    for i in [4, 3, 2, 1, 0]:
        head = ListNode(i, head)
    t = 2
    print(sol.removeNthFromEnd(head, t))

160. 链表相交

力扣题目链接(opens new window)

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

# — coding: utf-8 –

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def getIntersectionNode(self, headA, headB):
        """
        :type head1, head1: ListNode
        :rtype: ListNode
        """
        # if not headA or not headB:
        #     return None
        # pa, pb = headA, headB
        # while pa != pb:
        #     if pa is None:
        #         pa = headB
        #     else:
        #         pa = pa.next
        #     if pb is None:
        #         pb = headA
        #     else:
        #         pb = pb.next
        # return pa

        # 我们求出两个链表的长度,并求出两个链表长度的差值,然后让curA移动到,和curB 末尾对齐的位置
        lenA, lenB = 0, 0
        cur = headA
        while cur:         # 求链表A的长度
            cur = cur.next
            lenA += 1
        cur = headB
        while cur:         # 求链表B的长度
            cur = cur.next
            lenB += 1
        # 搞俩个头
        curA, curB = headA, headB
        # 交换俩个头,让curB为最长链表的头,lenB为其长度
        if lenA > lenB:
            curA, curB = curB, curA
            lenA, lenB = lenB, lenA
        # 让curA和curB在同一起点上(末尾位置对齐)
        for _ in range(lenB - lenA):
            curB = curB.next
        #  遍历curA 和 curB,遇到相同则直接返回
        while curA:
            if curA == curB:
                return curA
            else:
                curA = curA.next
                curB = curB.next
        return None

142.环形链表II

力扣题目链接(opens new window)

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

为了表示给定链表中的环,使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。 如果 pos 是 -1,则在该链表中没有环。

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

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

class Solution(object):
    def detectCycle(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        slow, fast = head, head
        while fast and fast.next:
            # 慢指针一次移动一个,快指针一次移动两个
            slow = slow.next
            fast = fast.next.next
            # 相遇
            if slow == fast:
                index1 = head
                index2 = slow
                while index2 != index1:
                    index1 = index1.next
                    index2 = index2.next
                # 返回相交的指针
                return index1

总结

  • 链表的种类主要为:单链表,双链表,循环链表
  • 链表的存储方式:链表的节点在内存中是分散存储的,通过指针连在一起。
  • 链表是如何进行增删改查的。
  • 数组和链表在不同场景下的性能分析。

猜你喜欢

转载自blog.csdn.net/lxwssjszsdnr_/article/details/130656640
今日推荐